假设我有一个已加载的HTML文件,我运行以下查询:
但是当我尝试以下操作时,会出现PHP错误,提示无法添加节点:
$url = 'http://www.fangraphs.com/players.aspx';
$html = file_get_contents($url);
$myDom = new DOMDocument;
$myDom->formatOutput = true;
@$myDom->loadHTML($html);
$anchor = $xpath->query('//a[contains(@href,"letter")]');
这给了我一个类似于以下锚点的列表:
<a href="players.aspx?letter=Aa">Aa</a>
但我需要一种只获取“players.aspx?letter=Aa”的方法。
我想尝试:
$anchor = $xpath->query('//a[contains(@href,"letter")]/@href');
但是当我尝试以下操作时,会出现PHP错误,提示无法添加节点:
$xpath = new DOMXPath($myDom);
$newDom = new DOMDocument;
$j = 0;
while( $myAnchor = $anchor->item($j++) ){
$node = $newDom->importNode( $myAnchor, true ); // import node
$newDom->appendChild($node);
}
有什么办法可以仅获取第一个查询所选取的href标签的值吗?谢谢!
xpath
和newDom
的初始化位置。 - Explosion Pills