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

时间:2011-04-18 20:06:46

标签: php xml

我正在向外部公司的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变量?

1 个答案:

答案 0 :(得分:0)

您可以使用php xpath()功能。

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

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