如何使用编码器读取 Xml 数据


How to Read Xml data using codeigniter?

我想在codeigniter中使用curl读取xml数据。我创建了一个帮助程序文件,该文件将从以下 url 读取数据:http://www.ekidata.jp/api/l/11302.xml 但问题是我无法从此 url 读取数据。请帮忙这是我的助手文件结构:

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 {
    }
}

}

这是我的控制器:

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

以下是我的观点:

<?php echo ekidata('l', 11302);?>

我已经测试了您的代码并且它工作正常,我看到的唯一问题是您正在尝试回显一个对象(返回的XML变量),请尝试:

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

您应该看到文件中的所有XML对象,然后您可以循环该对象并获取所需的数据。所以如果你想要第一个站名,你可以这样得到它:

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

并在所有站点上循环:

foreach($r->station as $station) {
    echo $station->station_name.'<br/>';
 }