假设我有一个已加载的 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")]');
这给了我这些 anchor 的列表,如下所示:
<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 标签的值吗?谢谢!
最佳答案
使用:
//a/@href[contains(., 'letter')]
这会选择任何 a
的任何 href
属性,其字符串值(属性的)包含字符串 "letter"
.
关于PHP Xpath : Get all href's that contain "letter",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10591700/