Search code examples
phpxmlsimplexml

Read XML data from string


now i need to ask this, have this XML:

<?xml version="1.0" encoding="utf-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:web="http://webservice.telemetry.udo.fors.ru/" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
    <soapenv:Header>
        <wsse:Security soapenv:mustUnderstand="1">
            <wsse:UsernameToken>
               <wsse:Username/>
               <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText"/>
            </wsse:UsernameToken>
        </wsse:Security>
    </soapenv:Header>
    <soapenv:Body>
      <web:storeTelemetryList xmlns="http://webservice.telemetry.udo.fors.ru/">
          <telemetryWithDetails xmlns="">
              <telemetry>
                 <coordX>-108.345268</coordX>
                 <coordY>25.511797</coordY>
                 <date>2020-04-16T16:48:07Z</date><glonass>0</glonass>
                 <gpsCode>459971</gpsCode>
                 <speed>0</speed>
              </telemetry>
          </telemetryWithDetails>
       </web:storeTelemetryList>
   </soapenv:Body>
</soapenv:Envelope>

and im using simplexml on PHP to read it but i get the error "Trying to get property 'telemetryWithDetails' of non-object" when i try to get the data in coordx, coordy,date, gpscode and speed node but i cant get there here is my code:

$string = <<<XML
<?xml version="1.0" encoding="utf-8"?>
<soapenv:Envelope...(same from above)
XML;

$xml = new SimpleXMLElement($string);

echo $xml->Body->storeTelemetryList->telemetryWithDetails;

if i put "->telemetryWithDetails->telemetry->coordX" i get "Trying to get property 'telemetry' of non-object, Trying to get property 'coordX' of non-object" and the same if use "simplexml_load_string" Hope you can help me thanks


Solution

  • A simple solution is to use XPath and describe the "path" to the values you want :

    $xml = simplexml_load_string($xmlstring);
    $telemetries = $xml->xpath('/soapenv:Envelope/soapenv:Body/web:storeTelemetryList/telemetryWithDetails/telemetry');
    $telemetry = $telemetries[0] ;
    
    $coordX = (string) $telemetry->xpath('./coordX')[0] ;
    $coordY = (string) $telemetry->xpath('./coordY')[0] ;
    
    echo $coordX ; //-108.345268
    echo $coordY ; // 25.511797
    

    XPath returns always a collection, so select the first node with [0]. The (string) conversion is used to extract the text value inside the node.