drmlxgmqn18198265 2013-03-25 01:22
浏览 32
已采纳

如何使用PHP解析此XML?

I would like to do parse XML for the url: http://www.opencellid.org/cell/get?key=myapikey&mcc=250&mnc=99&cellid=29513&lac=0

I am the beginner of PHP and tried the code as below:

$url = "http://www.opencellid.org/cell/get?key=myapikey&mcc=250&mnc=99&cellid=29513&lac=0";

$xml = simplexml_load_file($url) or die("feed not loading");

print_r($xml);

var_dump($xml);

I would like to do echo for each attribute e.g. lat, lon, range.. for this XML url.

I found many resource in stackoverflow which the XML is quite standard. I cannot find an example which is used for this format of XML:

Anyone could give me an idea? Thanks.

  • 写回答

3条回答 默认 最新

  • doudang2817 2013-03-25 01:29
    关注
    $url = "http://www.opencellid.org/cell/get?key=myapikey&mcc=250&mnc=99&cellid=29513&lac=0";
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $data = curl_exec($ch);
    $status = curl_getinfo($ch,CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if($status==200){
        $x = new SimpleXMLElement($data,LIBXML_NOCDATA);
        echo 'lat: '.$x->cell['lat'];
        echo 'lon: '.$x->cell['lon'];
        echo 'range: '.$x->cell['range'];
    }
    

    Update: This is an alternative to curl. If you have curl installed, use curl, it is faster.

    $url = "http://www.opencellid.org/cell/get?key=myapikey&mcc=250&mnc=99&cellid=29513&lac=0";
    
    $data = file_get_contents($url);
    $x = new SimpleXMLElement($data,LIBXML_NOCDATA);
    $lat = $x->cell['lat'];
    $lng = $x->cell['lon'];
    $range = $x->cell['range'];
    
    echo 'lat: '.$lat.'<br>';
    echo 'lng: '.$lng.'<br>';
    echo 'range: '.$range.'<br>';
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部