Search code examples
phpxmlobjectxpathsimplexml

How parsing out XML file with namespaces?


I know similar questions were posted before, but I can't parse out this XML file with namespaces.

Here is the link to it because it's too big to post here: https://tsdrapi.uspto.gov/ts/cd/casestatus/sn86553893/info.xml

I tried using simplexml_load_file but that does not create xml object. Then I found similar problems and try something like this, provided I already downloaded file named it 86553893.xml

Here is my php code:

$xml= new SimpleXMLElement("86553893.xml");
                            foreach($xml->xpath('//com:ApplicationNumber') as $event) {
                                var_export($event->xpath('com:ApplicationNumberText'));
                        }

Solution

  • You will have to register the namespaces on each element you want to use them:

    $xml= new SimpleXMLElement("86553893.xml");
    $xml->registerXpathNamespace('com', 'http://www.wipo.int/standards/XMLSchema/Common/1');
    foreach ($xml->xpath('//com:ApplicationNumber') as $event) {
      $event->registerXpathNamespace(
        'com', 'http://www.wipo.int/standards/XMLSchema/Common/1'
      );                         
      var_export($event->xpath('com:ApplicationNumberText'));
    }
    

    This is different in DOM, you use an DOMXPath instance, so it is only a single object and you will have to register the namespaces only once.

    $dom = new DOMDocument();
    $dom->load("86553893.xml");
    $xpath = new DOMXpath($dom);
    $xpath->registerNamespace('com', 'http://www.wipo.int/standards/XMLSchema/Common/1');
    
    foreach ($xpath->evaluate('//com:ApplicationNumber') as $event) {
      var_export($xpath->evaluate('string(com:ApplicationNumberText)', $event));
    }