解析/解释PHP中从web服务检索到的XML


Parsing/Interpreting XML retrieved from a web service in PHP

我正在向外部公司的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的xpath()函数

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

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