我正在向外部公司的Web服務發送HTTP GET請求。這個回來很好,但我遇到了解釋什麼會回來的問題。該響應以XML格式發送。我試圖使用SimpleXML(我承認,我不熟悉),並且無法弄清楚。我需要做的是將XML中收到的內容分配給PHP變量,然後回顯它。我需要分配的變量是「SessionToken」到$ sessionid。我該怎麼做呢?解析/解釋從PHP中的Web服務檢索到的XML
這裏是我的代碼示例:
error_reporting(E_ALL);
$request = 'http://ws.examplesite.com/test/test.asmx/TestFunction?Packet=<Packet><Email>[email protected]</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手冊。網上有數以千計的教程如何做到這一點。 – cweiske 2011-04-18 20:16:03