【问题标题】:how to properly get data from an XML SOAP response in PHP?how to properly get data from an XML SOAP response in PHP?
【发布时间】:2022-12-01 21:13:19
【问题描述】:

I'm able to access part of the XML record but the problem is the returned value is presented in this format below:

SimpleXMLElement Object
(
    [0] => 
1234567
)

And if I use inspect element this is what it shows:

<xx>
   <yy>
      <a>1</a>
      <b>2</b>
      <c>3</c>
      <d>4</d>
   </yy>
   <zz Type="type">
      <e>5</e>
      <f>6</f>
      <g>
         <h>7</h>
      </g>
   </zz>
</xx>

SOAP XML Response: (The actual SOAP response have < and > converted to &amp;lt; and &amp;gt; I just changed it here to make it more readable)

<s:envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:body>
<processrequestresponse xmlns="http://zzz.org/">
<processrequestresult>
<xx>
   <yy>
      <a>1</a>
      <b>2</b>
      <c>3</c>
      <d>4</d>
   </yy>
   <zz Type="type">
      <e>5</e>
      <f>6</f>
      <g>
         <h>7</h>
      </g>
   </zz>
</xx>
</processrequestresult>
</processrequestresponse>
</s:body>
</s:envelope>

Code:

$xml = simplexml_load_string($response);
$data    = $xml->xpath("//s:Body/*")[0];
        $details = $data->children("http://zzz.org/");
        $test    = $details->ProcessRequestResult[0];
        echo '<pre>';
        print_r($test);

So my question is how do I access the values for a,b,c,d,e,f, and g individually?

【问题讨论】:

  • Is your expected output simply 1 through 7, in your example? If not, please edit the question and add the exact expected output.
  • @JackFleeting it is, so I only need to get access to the data stored in <a> or <b> or <c> etc

标签: php xml soap


【解决方案1】:

Try it this way:

$data = $xml->xpath('//*//text()');

foreach ($data as $datum) {
    if (strlen(trim($datum))>0)
    echo trim($datum)."

";
}

Output should be 1 through 7.

【讨论】:

  • thanks, will give this a try. do you by chance know what that part of the code is called when it does that? i.e showing numbers but inspect element shows it's actually more?
  • it works only if I manually set the XML into a variable, but if I try to use the response from the SOAP request it doesn't work. Maybe because the SOAP response has transformed < and > to "&lt;" and "&gt;"?
  • I got it working by doing html_entity_decode on the response first. thank you for this! but can you explain the code more so that I can learn more about dealing with XML in the future?
猜你喜欢
  • 2022-12-02
  • 2022-12-02
  • 2022-12-27
  • 2022-12-01
  • 2022-12-27
  • 2019-02-14
  • 2022-12-26
  • 2022-12-01
  • 2022-11-01
相关资源
最近更新 更多