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.
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('&','&',$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/>';
}
}
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With