dsgft1486 2011-04-18 20:06
浏览 38
已采纳

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

I am sending a HTTP GET request to the web service of an external company. This is coming back fine, but I am running into problems with the interpretation of what comes back. The response is sent in XML. I have tried to use SimpleXML (which I admit, I am not familiar with) and cannot figure it out. What I need to do is assign something received in the XML to a PHP variable and then echo it. The variable I need to assign is "SessionToken" to $sessionid. How do I do this?

Here is an example of my code:


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;


Here is an example of the response:


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


How can I extract variables from XML and assign them to PHP variable?

  • 写回答

1条回答 默认 最新

  • dsnpjz6907 2011-04-18 20:16
    关注

    You can use the php xpath() function.

    In you example I would do something like this

    $xml = simplexml_load_string($response);
    $xpathresult = $xml->xpath("//SessionToken");
    list(,$sessionToken) = each($xpathresult)
    if($sessionToken)
    {
      //Code here
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算