从字符串中读取 XML 数据

Read XML data from string

现在我需要问这个,有这个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>

我在 PHP 上使用 simplexml 来读取它,但是当我尝试获取 coordx、coordy、date、gpscode 和 speed 节点中的数据时出现错误 "Trying to get property 'telemetryWithDetails' of non-object" 但我无法获取这是我的代码:

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

$xml = new SimpleXMLElement($string);

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

如果我输入“->telemetryWithDetails->telemetry->coordX”,我会得到 "Trying to get property 'telemetry' of non-object, Trying to get property 'coordX' of non-object" 如果使用 "simplexml_load_string",我会得到同样的结果 "simplexml_load_string" 希望你能帮助我,谢谢

一个简单的解决方案是使用 XPath 并将 "path" 描述为您想要的值:

$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 始终是一个集合,因此 select 第一个节点带有 [0](string) 转换用于提取节点内的文本值。