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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 14:11:53  来源:igfitidea点击:

SimpleXML get element content based on attribute value

phpcss-selectorssimplexml

提问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 DocSumnodes that have an Itemchild with value "Author" in the Nameattribute 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 之间来回转换,因为这似乎是遍历树的唯一记录方式......