Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SimpleXML get element content based on attribute value [duplicate]

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:

<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.

like image 759
Bob Avatar asked Jan 19 '11 14:01

Bob


1 Answers

This XPath query 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:

$nodes = $xml->xpath('//DocSum[Item[@Name="Author" and .="Oliveira GC"]]');
$book = $nodes[0];
print_r($book);
like image 175
scoffey Avatar answered Sep 21 '22 17:09

scoffey