说我有一个已加载的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标记的值吗?谢谢!
最佳答案
您的XPath查询返回的是属性本身(即DOMAttr
对象)而不是元素(即DOMElement
对象)。很好,这似乎就是您想要的,但是将它们附加到文档中就是问题所在。 DOMAttr
不是文档树中的独立节点。它与DOMElement
相关联,但通常不是 child 。因此,直接将DOMAttr
附加到文档是无效的。
从the W3C specs:
可以将DOMAttr
与DOMElement
关联并附加该元素,或者拉出DOMAttr
的值并根据需要使用它。
要仅附加其纯文本值,请在DOMText
节点中使用其值并将其附加。例如,更改此行:
$newDom->appendChild($node);
对此:
$newDom->appendChild(new DOMText($node->value));
关于PHP Xpath : Get all href's that contain "letter",我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10591700/