Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Output HTML using PHP DOM [duplicate]

Im trying to echo HTML using PHP DOM:

$doc = new \DomDocument('1.0', 'UTF-8');
$doc->loadHTMLFile("http://www.nu.nl");

$tags = $doc->getElementsByTagName('a');

echo $doc->saveHTML($tags);

This is getting me a blank page. I also tried:

$doc = new DOMDocument();
$doc->loadHTMLFile("http://www.nu.nl");

$links = $doc->getElementsByTagName('a');
foreach ($links as $link) {
  echo $link->getAttribute('href') . '<br />';

}

This is getting me the "href" as plain text. I have Googled for hours now and tried many things but I can't figure out how to output HTML as HTML.

like image 584
Youss Avatar asked Sep 12 '26 10:09

Youss


2 Answers

here is a fix that will add the root url for relative links

$pageurl = "http://www.nu.nl";
$html = file_get_contents($pageurl);
$html = str_replace('&','&amp;',$html);
$doc = new DOMDocument();
@$doc->loadHTML($html);
$links = $doc->getElementsByTagName('a');
foreach ($links as $link) {
    $myLink = $link->getAttribute('href');
    if (substr($myLink,0,7) == 'http://') {
        echo '<a href="'.$myLink.'">'.$myLink.'</a><br/>';
    } else {
        echo '<a href="'.$pageurl.$myLink.'">'.$myLink.'</a><br/>';
    }
}
like image 191
Anas Bouhtouch Avatar answered Sep 14 '26 00:09

Anas Bouhtouch


You probably want something like this doing:

$doc = new DOMDocument();
$doc->loadHTMLFile("http://www.nu.nl");

$links = $doc->getElementsByTagName('a');
foreach ($links as $link) {
    $thelinks[] = '<a href="' . $link->getAttribute('href') . '">' . trim(preg_replace('/\s{2,}/', '', $link->textContent)) . '</a>';
}

var_dump($thelinks);
like image 31
Farkie Avatar answered Sep 14 '26 00:09

Farkie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!