Steve
Steve

Reputation: 546

How to load xml data with namespace

So the XML I am trying to load looks something like this:

<tns:PersonListOutput xmlns:tns="http://www.example.com/api/person">
  <tns:LastName>Doe</tns:LastName>
  <tns:TransmissionDate>2018-03-02T10:16:23</tns:TransmissionDate>
  <tns:People>
    <tns:Person>
      <tns:Name>John Doe</tns:Name>
      <tns:RevisionDate>2017-08-10T01:45:40</tns:RevisionDate>
    </tns:Person>
    <tns:Person>
      <tns:Name>Jane Doe</tns:Name>
      <tns:RevisionDate>2017-08-10T01:45:43</tns:RevisionDate>
    </tns:Person>
  </tns:People>
</tns:PersonListOutput>

I am loading this data from a URL using the following code:

$response_xml_data = file_get_contents($URL);
$data = simplexml_load_string($response_xml_data);

I was finally able to reference the top level properties but am unable to get the properties of the Person. This is how I finally got it working if someone could help with the Person access or suggest a better way to do it.

$data->registerXPathNamespace('tns', 'http://www.example.com/api/person');
$LastName = $data->xpath('//tns:LastName ');
$TransmissionDate = $data->xpath('//tns:TransmissionDate');

echo $LastName[0];
echo "<br/>";
echo $TransmissionDate[0];

Upvotes: 1

Views: 76

Answers (1)

ishegg
ishegg

Reputation: 9947

You need to keep prepending the namespace to your XPath query elements, like so:

//tns:People/tns:Person/tns:Name

That will give you all the Name elements inside Person, inside People.

$data = simplexml_load_string($response_xml_data);
$data->registerXPathNamespace('tns', 'http://www.example.com/api/person');
$LastName = $data->xpath('//tns:LastName ');
$TransmissionDate = $data->xpath('//tns:TransmissionDate');
$people = $data->xpath('//tns:People/tns:Person/tns:Name');
var_dump($people);

Demo

Result

array (size=2)
  0 => 
    object(SimpleXMLElement)[4]
      public 0 => string 'John Doe' (length=8)
  1 => 
    object(SimpleXMLElement)[5]
      public 0 => string 'Jane Doe' (length=8)

Upvotes: 1

Related Questions