假设我有一个已加载的 html 文件,我运行以下查询:
$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 标记的值吗?谢谢!