A
A
astler2015-10-12 17:59:19
PHP
astler, 2015-10-12 17:59:19

How to access a branch in PHP in SimpleXML if a namespace is used?

There is such an XML

<?xml version="1.0" encoding="UTF-8" ?>
<tns:RequestAndResponse xmlns:tns="com.dtn.aghost.weather.weatherService">
  <request>
    <tns:Credentials>
      <usernamePasswordCombo>
        <username>E0E0E0</username>
        <password>E0E0E0</password>
      </usernamePasswordCombo>
    </tns:Credentials>
  </request>

  <response>
    <tns:AccountToken expires="2015-10-12T15:20:13.000Z">
      <Token>E0E0E0E1E1E1</Token>
      <URLEncodedToken>E0E0E0E1E1E1</URLEncodedToken>
    </tns:AccountToken>
  </response>
</tns:RequestAndResponse>

In PHP, I load it with simplexml_load_string, and that's it. I can't figure out how namespace works in SimpleXML. Please tell me how can I get to the Token if I loaded the xml like this:
$xml = simplexml_load_string($result);
Thank you!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Skobkin, 2015-10-12
@astler

For example, like this and this .
Something like this:

<?php

$xmlString = <<<'XML'
<?xml version="1.0" encoding="UTF-8" ?>
<tns:RequestAndResponse xmlns:tns="com.dtn.aghost.weather.weatherService">
  <request>
    <tns:Credentials>
      <usernamePasswordCombo>
        <username>E0E0E0</username>
        <password>E0E0E0</password>
      </usernamePasswordCombo>
    </tns:Credentials>
  </request>

  <response>
    <tns:AccountToken expires="2015-10-12T15:20:13.000Z">
      <Token>E0E0E0E1E1E1</Token>
      <URLEncodedToken>E0E0E0E1E1E1</URLEncodedToken>
    </tns:AccountToken>
  </response>
</tns:RequestAndResponse>
XML;

$xml = new SimpleXMLElement($xmlString);

foreach ($xml->xpath('//tns:Credentials') as $credentials) {
    var_dump($credentials->usernamePasswordCombo->username, $credentials->usernamePasswordCombo->password);
}

foreach ($xml->xpath('//tns:AccountToken') as $token) {
    var_dump($token->Token, $token->URLEncodedToken);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question