【问题标题】:PHP cURL, extract an XML responsePHP cURL,提取 XML 响应
【发布时间】:2010-10-08 09:21:09
【问题描述】:

我在服务器上调用 PHP cURL 方法,响应是 XML 类型。 cURL 将输出(删除标签后)保存在标量类型变量中。有没有办法将它存储在对象/哈希/数组中以便于解析?

【问题讨论】:

  • 您能否详细说明“删除标签后”的含义。

标签: php curl


【解决方案1】:
<?php
function download_page($path){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$path);
    curl_setopt($ch, CURLOPT_FAILONERROR,1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 15);
    $retValue = curl_exec($ch);          
    curl_close($ch);
    return $retValue;
}

$sXML = download_page('http://alanstorm.com/atom');
$oXML = new SimpleXMLElement($sXML);

foreach($oXML->entry as $oEntry){
    echo $oEntry->title . "\n";
}

【讨论】:

【解决方案2】:

只需在 XML 响应的回显之前添加 header('Content-type: application/xml');,您就会看到一个 XML 页面。

【讨论】:

    【解决方案3】:

    例子:

    <songs>
    <song dateplayed="2011-07-24 19:40:26">
        <title>I left my heart on Europa</title>
        <artist>Ship of Nomads</artist>
    </song>
    <song dateplayed="2011-07-24 19:27:42">
        <title>Oh Ganymede</title>
        <artist>Beefachanga</artist>
    </song>
    <song dateplayed="2011-07-24 19:23:50">
        <title>Kallichore</title>
        <artist>Jewitt K. Sheppard</artist>
    </song>
    

    然后:

    <?php
    $mysongs = simplexml_load_file('songs.xml');
    echo $mysongs->song[0]->artist;
    ?>
    

    浏览器上的输出:游牧民族之船

    学分:http://blog.teamtreehouse.com/how-to-parse-xml-with-php5

    【讨论】:

      【解决方案4】:

      不,CURL 没有解析 XML 的任何内容,它对返回的内容一无所知。它充当获取内容的代理。由你决定如何处理它。

      尽可能使用 JSON(和 json_decode) - 如果不可能,使用任何 XML 库进行解析会更容易,例如 DOMXML: http://php.net/domxml

      【讨论】:

      • 我同意这一点。但是为什么没有显示标签。我做一个回声。是浏览器的原因吗?
      • 是的,浏览器将XML视为(X)HTML,所以如果遇到>或
      • 如果你回显 htmlentities(...) 你会看到完整的 XML
      【解决方案5】:
      $sXML = download_page('http://alanstorm.com/atom');
      // Comment This    
      // $oXML = new SimpleXMLElement($sXML);
      // foreach($oXML->entry as $oEntry){
      //  echo $oEntry->title . "\n";
      // }
      // Use json encode
      $xml = simplexml_load_string($sXML);
      $json = json_encode($xml);
      $arr = json_decode($json,true);
      print_r($arr);
      

      【讨论】:

      • download_page(),真的吗?至少当你建议一个函数时,坚持使用内置函数或定义你提议的函数。新手很容易迷路。我建议您对其进行编辑并至少用一个简单的 file_get_contents() 替换它。
      【解决方案6】:

      简单的加载xml文件..

      $xml = @simplexml_load_string($retValuet);
      
      $status = (string)$xml->Status; 
      $operator_trans_id = (string)$xml->OPID;
      $trns_id = (string)$xml->TID;
      

      ?>

      【讨论】:

        猜你喜欢
        • 2020-08-14
        • 1970-01-01
        • 1970-01-01
        • 2015-05-21
        • 2012-02-05
        • 2013-07-23
        • 1970-01-01
        • 2013-10-25
        • 1970-01-01
        相关资源
        最近更新 更多