【问题标题】:Parsing/Interpreting XML retrieved from a web service in PHP解析/解释从 PHP 中的 Web 服务检索的 XML
【发布时间】:2011-04-18 20:06:46
【问题描述】:

我正在向外部公司的 Web 服务发送 HTTP GET 请求。这很好,但我在解释返回的内容时遇到了问题。响应以 XML 格式发送。我曾尝试使用 SimpleXML(我承认,我不熟悉)但无法弄清楚。我需要做的是将 XML 中接收到的内容分配给 PHP 变量,然后回显它。我需要分配的变量是“SessionToken”到 $sessionid。我该怎么做?

这是我的代码示例:


error_reporting(E_ALL);

$request =  'http://ws.examplesite.com/test/test.asmx/TestFunction?Packet=<Packet><Email>test@example.com</Email><Password>testpassword</Password></Packet>';

$session = curl_init($request);

curl_setopt($session, CURLOPT_HEADER, true);

curl_setopt($session, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($session);

curl_close($session);

$status_code = array();
preg_match('/\d\d\d/', $response, $status_code);

switch( $status_code[0] ) {
    case 200:
        break;
    case 503:
        die('Your call to Web Services failed and returned an HTTP status of 503. That means: Service unavailable. An internal problem prevented us from returning data to you.');
        break;
    case 403:
        die('Your call to Web Services failed and returned an HTTP status of 403. That means: Forbidden. You do not have permission to access this resource, or are over your rate limit.');
        break;
    case 400:
        die('Your call to Web Services failed and returned an HTTP status of 400. That means:  Bad request. The parameters passed to the service did not match as expected. The exact error is returned in the XML response.');
        break;
    default:
        die('Your call to Web Services returned an unexpected HTTP status of:' . $status_code[0]);
}


if (!($xml = strstr($response, '<?xml'))) {
    $xml = null;
}

echo $xml;


以下是响应示例:


<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://ws.example.com/resumes/">
  <Packet>
    <Errors />
    <SessionToken>1234567890</SessionToken>
  </Packet>
</string>


如何从 XML 中提取变量并将它们分配给 PHP 变量?

【问题讨论】:

  • 阅读 PHP 手册。网络上有数以千计的教程如何做到这一点。

标签: php xml


【解决方案1】:

你可以使用phpxpath()函数。

在你的例子中,我会做这样的事情

$xml = simplexml_load_string($response);
$xpathresult = $xml->xpath("//SessionToken");
list(,$sessionToken) = each($xpathresult)
if($sessionToken)
{
  //Code here
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-19
    • 2011-08-13
    • 2018-12-28
    • 2017-01-19
    相关资源
    最近更新 更多