Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP DomDocument editing all links

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.

like image 693
Solomon Closson Avatar asked Mar 18 '13 03:03

Solomon Closson


1 Answers

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();
like image 57
Sudhir Bastakoti Avatar answered Oct 19 '22 05:10

Sudhir Bastakoti