Php 获取具有itemprop属性的所有元素
我正在使用PHP DomDocument,并试图找出如下内容:Php 获取具有itemprop属性的所有元素,php,domdocument,Php,Domdocument,我正在使用PHP DomDocument,并试图找出如下内容: <div itemprop='movie'>Fight Club</div> <span itemprop='musician'>Ozzy Osbourne</span> function getItemprops(){ foreach($this->dom->getAttribute("itemprop") as $buffer) {
<div itemprop='movie'>Fight Club</div>
<span itemprop='musician'>Ozzy Osbourne</span>
function getItemprops(){
foreach($this->dom->getAttribute("itemprop") as $buffer) {
$itempropList = array(
'theNodeValue' => $buffer->nodeValue,
'theItemprop' => $buffer->getAttribute("itemprop")
)
return $itempropList;
}
}
我的代码应该在以下行的某处获得一个数组:
array (
array(
0 =>
"theNodeValue" => "Fight Club",
"theItemprop" => "movie"
1 =>
"theNodeValue" => "Fight Club",
"theItemprop" => "movie"
)
)
不幸的是,我的代码返回了致命错误:调用未定义的方法DOMDocument::getAttribute()
所以基本上,我想选择所有itemprop=”“
,并将它们放入数组中
谢谢你的帮助 首先需要使用XPath选择具有所需属性的所有节点,然后循环返回节点以获取文本值和属性值;像这样
$d = new DOMDocument();
$d->loadHTML($xmlsource);
$xpath = new DOMXPath($d);
$nodes = $xpath->query('//*[@itemprop]'); //this catches all elements with itemprop attribute
foreach ($nodes as $node) {
// do your stuff here with $node