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/>';
    
     }
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题