Search code examples
phpxmlcodeignitercurlcodeigniter-2

How to Read Xml data using codeigniter?


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);?>

Solution

  • 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/>';
    
     }