seal
seal

Reputation: 520

Get element inside of multiple namespaces xml

I have tried to get the element DistrictName inside of namespaces `//ns1:Location//ns1:District, but but nothing is returned. Here's what I've done so far.

foreach($xml1->xpath('//ns1:Venue') as $header){
    $result = ($header->xpath('//ns1:Venue//ns1:Location//ns1:District//ns1:DistrictName')); // Should output 'something'.
    echo "Local2: " . (string) $result[0]. "</br>";
}

soap_response_xml:

...
<ns1:Venue>
  <ns1:Name>Rock</ns1:Name>
  <ns1:Contact>
    <ns1:Name>Rock</ns1:Name>
  </ns1:Contact>
  <ns1:Location>
    <ns1:District>
      <ns2:DistrictId>11</ns2:DistrictId>
      <ns2:DistrictName>XXXXXXX</ns2:DistrictName>
    </ns1:District>
    <ns1:Municipaly>
      <ns2:MunicipalityId>1111</ns2:MunicipalityId>
      <ns2:MunicipalityName>XXXXXXXXX</ns2:MunicipalityName>
    </ns1:Municipaly>
  </ns1:Location>
</ns1:Venue>

what I'm doing wrong?

Upvotes: 1

Views: 244

Answers (1)

M. Page
M. Page

Reputation: 2814

If your XML is in a string, the simplest is maybe to remove namespaces:

$string = str_replace(array('ns1:', 'ns2:'), array('', ''), $string);
$xml = new SimpleXMLElement($string);
foreach($xml->xpath('//Venue') as $header){
    $result = ($header->xpath('Location/District/DistrictName')); // Should output 'something'.
    echo "Local2: " . (string) $result[0]. "</br>";
}

Also: don't use // when it is not necessary. // means "descendant". The path separator is /

Upvotes: 2

Related Questions