如何使用PHP从Web服务获取XML数据?

时间:2012-04-06 13:10:27

标签: php .net xml web-services soap

我需要从.NET Web服务访问响应,该服务以XML格式返回数据。 如何拆分返回的数据?例如,我想将数据解析为一些PHP变量:

$name = "Dupont";
$email = "charles.dupont@societe.com";

我一直在寻找如何做这件事很长时间没有找到正确的方法。

我的脚本是:

$result = $client->StudentGetInformation($params_4)->StudentGetInformationResult;

    echo "<p><pre>" . print_r($result, true) . "</pre></p>";

我页面中的回显是:

stdClass Object
(
    [any] => 0Successful10371DupontCharlescharles.dupont@societe.com1234charles.dupont@societe.comfalsefr-FR1003FIRST FINANCE1778AAA Département
)

网络服务响应格式为:

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <StudentGetInformationResponse xmlns="http://tempuri.org/">
      <StudentGetInformationResult>xml</StudentGetInformationResult>
    </StudentGetInformationResponse>
  </soap:Body>
</soap:Envelope>

我试过你的例子。但它并不能满足我的需要。 我需要拆分返回的值。我想获取数据并将它们放入PHP变量中:

$ name =&#34; Dupont&#34 ;; $ email =&#34; charles.dupont@societe.com" ;; 等...

不幸的是,你的例子的回声给出了:

object(stdClass)#1 (1) { ["StudentGetInformationResult"]=> object(stdClass)#11 (1) { ["any"]=> string(561) "0Successful10371DupontCharlescharles.dupont@societe.com1234charles.dupont@societe.comfalsefr-FR1003FIRST FINANCE1778AAA Département" } } 

1 个答案:

答案 0 :(得分:1)

您需要的唯一课程是SoapClient。您可以在PHP Documentation中使用很多示例。

示例:

try {
    $client = new SoapClient ( "some.aspx?wsdl" );
    $result = $client->StudentGetInformation ( $params_4 );

    $xml = simplexml_load_string($result->StudentGetInformationResult->any);
    echo "<pre>" ;

    foreach ($xml as $key => $value)
    {
        foreach($value as $ekey => $eValue)
        {
            print($ekey . " = " . $eValue . PHP_EOL);
        }
    }

} catch ( SoapFault $fault ) {
    trigger_error ( "SOAP Fault: (faultcode: {$fault->faultcode}, faultstring: {$fault->faultstring})", E_USER_ERROR );
}

输出

Code = 0
Message = Successful
stud_id = 10373
lname = Dupont
fname = Charles
loginid = charles.dupont@societe.com
password = 1234
email = charles.dupont@societe.com
extid = 
fdisable = false
culture = fr-FR
comp_id = 1003
comp_name = FIRST FINANCE
dept_id = 1778
dept_name = Certification CMF (Test web service)
udtf1 = 
udtf2 = 
udtf3 = 
udtf4 = 
udtf5 = 
udtf6 = 
udtf7 = 
udtf8 = 
udtf9 = 
udtf10 = 
Audiences =