Pregunta

Possible Duplicates:
Attribute Value Selection in SimpleXML
SimpleXML: Selecting Elements Which Have A Certain Attribute Value

I'm parsing an XML document and looking for a specific ID. The ID value is provided in the ArticleId element under attribute "pii". Raw XML:

<ArticleIdList>
    <ArticleId IdType="pubmed">12676398</ArticleId>
    <ArticleId IdType="pii">S0020729202004460</ArticleId>
</ArticleIdList>

Here is the entire document for reference: http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=pubmed&id=12676398&retmode=xml&rettype=abstract

Using simplexml_load_file(), I'm iterating through the document to obtain values. Here's how I'm getting to the ArticleId element:

$xml_PubmedArticle->PubmedData->ArticleIdList->ArticleId;

The problem is that attributes in ArticleId are random in order. Some ArticleId elements contain a "pii" value in the second element (as below), other records have a different attribute ("doi") in the second element.

SimpleXMLElement Object
(
    [ArticleId] => Array
        (
            [0] => 12676398
            [1] => S0020729202004460
        )
)

Variation:

SimpleXMLElement Object
(
    [ArticleId] => Array
        (
            [0] => 1234
            [1] => ABC123
            [2] => S002012345678
        )
)

I'm looking for the "S0002..." ID, which is identified in raw XML by attribute "pii".

How should I check/obtain a value based on a specific attribute?

¿Fue útil?

Solución

A couple ways:

foreach ($xml_PubmedArticle->PubmedData->ArticleIdList->ArticleId as $id) {
   foreach ($id->attributes() as $name => $value) {
      if ($value == 'pii') {
         //FOUND!
      }
   }
}

..or much simple xpath

$xml_PubmedArticle->xpath('PubmedData/ArticleIdList/ArticleId[@IdType="pii"]');

More specific xpaths are faster.

Also note that the first option will only iterate over the first ArticleIdList where as the XPath will return an array of all the items it finds.

Otros consejos

You can access a specific element by an attribute's value using xpath:

echo $xml_PubmedArticle->xpath('//ArticleIdList/ArticleId[@IdType="pii"]')[0];

See also Basic SimpleXML Usage in the manual.

A related question is: simplexml, returning multiple items with the same tag

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top