Search code examples
phpxmlsimplexml

How do I parse a specific child of xml output using simplexml?


I wish to parse this XML output, but only fetch the value for the "doi" record (e.g. 10.1038/onc.2012.390)

<ArticleIdList>
  <ArticleId IdType="pubmed">22986524</ArticleId>
  <ArticleId IdType="pii">onc2012390</ArticleId>
  <ArticleId IdType="doi">10.1038/onc.2012.390</ArticleId>
</ArticleIdList>

Can some advise me how to accomplish this? I've used

$xml = simplexml_load_file($query) or die("Error, feed not loading");

to create the object, but could not figure out the right syntax to move fw..

Thanks!


Solution

  • With SimpleXMLElement::xpath ( string $path ) function:

    $xml =  simplexml_load_file($query) or die("Error, feed not loading");
    $article_doi = (string) $xml->xpath('//ArticleId[@IdType="doi"]')[0];
    
    print_r($article_doi);
    

    The output:

    10.1038/onc.2012.390
    

    http://php.net/manual/en/simplexmlelement.xpath.php