2011-04-18 80 views
0

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

+0

阅读PHP手册。网上有数以千计的教程如何做到这一点。 – cweiske 2011-04-18 20:16:03

回答

0

您可以使用php xpath()函数。

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

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

像魅力一样工作谢谢你。 – Shattuck 2011-04-18 20:22:17

+0

不客气 – 2011-04-18 20:25:21