douji2283 2014-12-14 05:41
浏览 35
已采纳

如何使用codeigniter读取Xml数据?

I want to read xml data using curl in codeigniter. I have create a helper file which will read data from following url: http://www.ekidata.jp/api/l/11302.xml but problem is that i cannot read the data from this url. plz help Here is my helper file structure:

if (!function_exists('ekidata')) {

function ekidata($type, $code)
{

    $apiurl = 'http://www.ekidata.jp/api/'.$type.'/'.$code.'.xml';

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $apiurl);
    $response = curl_exec($ch);
    curl_close($ch);
    $xml = simplexml_load_string($response);
    if ($type == 'l') {
        return $xml;    
    } else {

    }
}

}

Here is my controller:

function ekidatatest()
{
    $this->load->view('ekidatatest');
}

Here is my view:

<?php echo ekidata('l', 11302);?>
  • 写回答

1条回答 默认 最新

  • dshfjsh_5455 2014-12-14 19:27
    关注

    I have tested your code and it works ok, the only issue i see is that you are tryin to echo an object (the returned XML variable), try:

    print_r (ekidata('l', 11302));

    and you should see all the xml object from the file, then you can loop on the object and get the data you need. So if you want the first station name you can get it like this:

    $r = ekidata('l', 11302);
    echo $r->station[0]->station_name;
    

    and to loop on all stations:

    foreach($r->station as $station) {
        echo $station->station_name.'<br/>';
    
     }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?