首页 > 解决方案 > 我如何从这个 SOAPXML 中获取 sessionid

问题描述

我想从这段 XML 代码中获取 sessionid:

<soapenv:envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <soapenv:header>
     <soapenv:body>
       <p725:loginresponse xmlns:p725="http://www.fleetboard.com/data">
         <p725:loginresponse sessionid="0001nABbah-I8f75oDrVbHrBgOv:s96fb0a4m3"></p725:loginresponse>
        </p725:loginresponse>
     </soapenv:body>
   </soapenv:header>
 </soapenv:envelope>

我已经尝试过了,但这不起作用:

$soap=simplexml_load_string($result);
$xml_response = $soap->children('http://schemas.xmlsoap.org/soap/envelope/')->Body()->children()->p725;
echo $session_id =  (int) $xml_response->session_id;

标签: phpxmlsoapxml-parsing

解决方案


有两种方法可以做到这一点。第一个是您当前正在执行的操作,但这涉及命名空间的各种更改,这意味着您需要继续获取正确的子元素和属性本身......

$soap=simplexml_load_string($result);
$xml_response = $soap->children("http://schemas.xmlsoap.org/soap/envelope/")->header->body;
$session_id = $xml_response->children("http://www.fleetboard.com/data")->loginresponse->loginresponse;
echo $session_id->attributes()->sessionid.PHP_EOL;

或者您可以使用 XPath,您需要先在文档中注册名称空间,然后选择loginresponse带有元素的sessionid元素。这将返回一个匹配列表,因此您必须使用[0]...

$soap=simplexml_load_string($result);
$soap->registerXPathNamespace("p725", "http://www.fleetboard.com/data");
$session_id = $soap->xpath("//p725:loginresponse/@sessionid");
echo $session_id[0];

推荐阅读