Thursday, 21 January 2016

XML : Parsing APFeeds XML with namespaces using PHP and SimpleXML

I'm having trouble getting the following information from this XML:

  <apcm:Property Name="EntitlementMatch" Id="urn:publicid:ap.org:product:41664" Value="AP Top News" />  <apcm:Property Name="EntitlementMatch" Id="urn:publicid:ap.org:product:42430" Value="AP Top News - International - Stories" />  <apcm:Property Name="EntitlementMatch" Id="urn:publicid:ap.org:package:100518" Value="AP Top News Package" />    

Specifically, I need the "ID" and "Value" fields.

Here's the main parts of the XML:

  <?xml version="1.0" encoding="utf-8" ?>  <feed xmlns="http://www.w3.org/2005/Atom" xmlns:apcm="http://ap.org/schemas/03/2005/apcm" xmlns:apnm="http://ap.org/schemas/03/2005/apnm" xmlns:georss="http://www.georss.org/georss" xmlns:o="http://w3.org/ns/odrl/2/">  ...  <entry xmlns="http://www.w3.org/2005/Atom">  ...  <apcm:Property Name="EntitlementMatch" Id="urn:publicid:ap.org:product:41664" Value="AP Top News" />  <apcm:Property Name="EntitlementMatch" Id="urn:publicid:ap.org:product:42430" Value="AP Top News - International - Stories" />  <apcm:Property Name="EntitlementMatch" Id="urn:publicid:ap.org:package:100518" Value="AP Top News Package" />  ...  </entry>  </feed>    

I have been looking at the following SO posts to try to figure it out, and this one is the most helpful so far: Identical nested XML elements with namespaces and PHP

And here's the code that I'm playing with:

      $ns_dc = $feed_entry->children($ns['apcm']);      echo "APCM children: " . count($ns_dc) . "<br />";        $inner_ns_dc = $feed_entry->children($ns_dc["apcm:Property"]);      echo "APCM Property Children: " . count($inner_ns_dc) . "<br />";        //$sxe = new SimpleXMLElement($feed_entry);        $sxe = new SimpleXMLElement($feed_entry->asXML());        foreach($sxe->apcm as $item) {          printf("%s\n", $item);      }      $sxe->registerXPathNamespace('apcm', 'http://ap.org/schemas/03/2005/apcm');      $result = $sxe->xpath('/apcm:Property:*');        echo "Result count: " . count($result) . "<br />";        foreach ($result as $sequenceNumber) {        echo $sequenceNumber . "<br />";      }    

No comments:

Post a Comment