PHP DomDocument editing all links

邮差的信 提交于 2020-01-13 03:25:10

问题


I am using the following code to grab html from another page and place it into my php page:

$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);

I want to change all instances of <a href="/somepath/file.htm"> so that I can prepend to it the actual domain instead. How can I do this?

So, it would need to change them to: <a href="http://mydomain.com/somepath/file.htm"> instead.


回答1:


try something like:

$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();


来源:https://stackoverflow.com/questions/15469274/php-domdocument-editing-all-links

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!