php SimpleXML 根据属性值获取元素内容
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4736417/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
SimpleXML get element content based on attribute value
提问by Bob
I'm trying to access the content of an element based on the value of an attribute. With PHP SimpleXML. I've got the following XML setup:
我正在尝试根据属性的值访问元素的内容。使用 PHP SimpleXML。我有以下 XML 设置:
<DocSum>
<Id>21242919</Id>
<Item Name="Author" Type="String">Nguyen T</Item>
<Item Name="Title" Type="String">[Hemoptysis and spontaneous rupture of a primary renal angiosarcoma: a case report.]</Item>
</DocSum>
<DocSum>
<Id>21242919</Id>
<Item Name="Author" Type="String">Oliveira GC</Item>
<Item Name="Title" Type="String">Disclosing ambiguous gene aliases by automatic literature profiling.</Item>
</DocSum>
<DocSum>
<Id>21242919</Id>
<Item Name="Author" Type="String">Vanderwall DE</Item>
<Item Name="Title" Type="String">Metformin and digestive disorders.</Item>
</DocSum>
These are books. In this case I'm trying to get the title. What I have so far is this:
这些是书。在这种情况下,我试图获得标题。到目前为止,我所拥有的是:
$xml = simplexml_load_file(url);
$docs = $xml->DocSum;
foreach($docs as $book){
// Each book individual
}
Where the comment is I tried a lot of things.
评论在哪里我尝试了很多东西。
回答by scoffey
This XPathquery on the SimpleXML object will return all DocSum
nodes that have an Item
child with value "Author" in the Name
attribute and value "Olivera GC" in the text node:
这个SimpleXML 对象上的XPath查询将返回所有DocSum
具有属性中Item
值为“Author”Name
且文本节点中值为“Olivera GC”的子节点的节点:
$nodes = $xml->xpath('//DocSum[Item[@Name="Author" and .="Oliveira GC"]]');
$book = $nodes[0];
print_r($book);
回答by ircmaxell
Well, I suspect the solution will be XPATH
...
好吧,我怀疑解决方案将是XPATH
......
If you're trying to get the title of a book by the id, you'd use the query:
如果您想通过 id 获取书名,则可以使用以下查询:
$query = '//DocSum/Id[contains(., "21232919")]';
If you're trying to search for the title of a book:
如果您正在尝试搜索一本书的书名:
$query = '//DocSum/Item[@Name="Title" AND contains(., "Metformin")]';
Then just run it:
然后运行它:
$xml = simplexml_load_file($url);
$results = $xml->xpath($query);
foreach ($results as $titleElement) {
$book = simplexml_import_dom(dom_import_simplexml($titleElement)->parentNode);
// Handle the book here
}
I'm converting back and forth between simplexml and domdocument since that appears to be the only documented way of traversing up the tree...
我在 simplexml 和 domdocument 之间来回转换,因为这似乎是遍历树的唯一记录方式......