【问题标题】:PHP DomDocument editing all linksPHP DomDocument 编辑所有链接
【发布时间】:2013-03-06 08:15:05
【问题描述】:

我正在使用以下代码从另一个页面抓取 html 并将其放入我的 php 页面:

$doc = new DomDocument;

// We need to validate our document before refering to the id
$doc->validateOnParse = true;
$doc->loadHtml(file_get_contents('{URL IS HERE}'));
$content = $doc->getElementById('form2');

echo $doc->SaveHTML($content);

我想更改<a href="/somepath/file.htm"> 的所有实例,以便可以在其前面添加实际域。我该怎么做?

因此,需要将它们改为:<a href="http://mydomain.com/somepath/file.htm">

【问题讨论】:

  • 如果我是你,我会避免使用DomDocument,而是直接使用正则表达式查找链接并进行编辑。
  • 怎么来的?我在 Stack Overflow 上的每一个地方,他们都说你应该为此使用 DomDocument。你能举个例子说明如何用正则表达式做到这一点吗?
  • 您为查找和替换任务创建了额外的对象。额外的解析时间和内存花费。试试看:stackoverflow.com/questions/4001328/…

标签: php domdocument


【解决方案1】:

尝试类似:

$xml = new DOMDocument(); 
$xml->loadHTMLFile($url); 
foreach($xml->getElementsByTagName('a') as $link) { 
   $oldLink = $link->getAttribute("href");
   $link->setAttribute('href', "http://mydomain.com/" . $oldLink);
}
echo $xml->saveHtml();

【讨论】:

  • 但是href 对于每个链接都是不同的,所以我只需要在它前面加上域。会不会是:$link->setAttribute('href', "http://mydomain.com/" + $link->getAttribute('href')); ??
  • 好的,很好,但我必须得到$content 而不是整个文档。无论如何,我从你的回答中弄清楚了。所以,你明白了。谢谢:)
猜你喜欢
  • 2010-09-22
  • 1970-01-01
  • 1970-01-01
  • 2014-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多