如何解析网页以将simplexml_import_dom更改为DOMXPath?

时间:2015-03-15 08:07:44

标签: php parsing

网页http://php.net中的所有链接都是使用code1中的simplexml_import_dom提取的。

code1
<?php
$dom = new DOMDocument();
$dom->loadHTMLFile('http://php.net');
$xml = simplexml_import_dom($dom);
$nodes = $xml->xpath('//a[@href]');
foreach ($nodes as $node) {
    echo $node['href'], "<br />\n";
}
?>

现在我想用DOMXPath解析网页,在code1中更改simplexml_import_dom 在code2中的DOMXPath中,code2中有一个错误,如何修复它?

code2
<?php
$html = file_get_contents('http://php.net');
$dom = new DOMDocument();
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$nodes = $xpath->query('//a[@href]');
foreach ($nodes as $node) {
    echo $node['href'], "<br />\n";
}
?>

2 个答案:

答案 0 :(得分:1)

从查询返回的数据是对象而不是数组!

如果你收到如下警告:

Warning: DOMDocument::loadHTML(): Tag nav invalid in Entity

在输出中,您可以在loadHTML函数调用之前添加此行

因为文档中使用了html5标记

libxml_use_internal_errors(true);

代码:

$html =  file_get_contents('http://php.net');
$dom = new DOMDocument();
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$nodes = $xpath->query('//a[@href]');
foreach ($nodes as $node) {
    echo $node->getAttribute("href"), "<br />\n";
}

答案 1 :(得分:0)

要解析所有href标记:

$sHtml = file_get_contents('http://php.net');
// var_dump( $sHtml );
$oDom = new DOMDocument( '1.0', 'utf-8' );
// Supress <DOCTYPE> notices
libxml_use_internal_errors(true);
$oDom->loadHTML('<?xml encoding="UTF-8">' . $sHtml );
// var_dump( $oDom );
$oXPath = new DOMXPath( $oDom );
$oNodes = $oXPath->query( '//a/@href' );
foreach( $oNodes as $oNode )
{
    // var_dump( $oNode );
    echo $oNode->nodeValue, "<br />\n";
}
// Supress <DOCTYPE> notices
libxml_use_internal_errors(false);
相关问题