假设我有一个已加载的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")]');
Run Code Online (Sandbox Code Playgroud)
这给了我一个这样的锚列表,如下所示:
<a href="players.aspx?letter=Aa">Aa</a>
Run Code Online (Sandbox Code Playgroud)
但我需要一种方法来获得"players.aspx?letter = Aa".
我以为我可以尝试:
$anchor = $xpath->query('//a[contains(@href,"letter")]/@href');
Run Code Online (Sandbox Code Playgroud)
但是这给了我一个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);
}
Run Code Online (Sandbox Code Playgroud)
知道如何只获取第一个查询选择的href标签的值吗?谢谢!