3

我想从 URL 读取 XML 数据。我的网址如下:

http://www.arrowcast.net/fids/mco/fids.asp?sort=city&city=&number=&airline=&adi=A

这是我的代码:

$Url="http://www.arrowcast.net/fids/mco/fids.asp?sort=city&city=&number=&airline=&adi=A";  
if (!function_exists('curl_init')){
    die('Sorry cURL is not installed!');
} 
   $ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $Url);   
$output = curl_exec($ch);
$resultCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// Close the cURL resource, and free system resources
curl_close($ch);

谁能告诉我如何读取 xml 数据?

4

3 回答 3

15

以下是一些示例代码(您的 PHP 安装中可能没有 XML 解析模块):

<?php

$url="http://www.arrowcast.net/fids/mco/fids.asp?sort=city&city=&number=&airline=&adi=A";
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);    // get the url contents

$data = curl_exec($ch); // execute curl request
curl_close($ch);

$xml = simplexml_load_string($data);
print_r($xml);

?>

变量$xml现在是一个多维键值数组,您应该很容易弄清楚如何从那里获取元素。

于 2012-07-19T04:13:25.997 回答
0
// the SAX way:
XMLReader myReader = XMLReaderFactory.createXMLReader();
myReader.setContentHandler(handler);
myReader.parse(new InputSource(new URL(url).openStream()));

// or if you prefer DOM:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new URL(url).openStream());
于 2012-07-19T07:20:07.990 回答
0

这是如何从 youtube 的 rss 提要中获取频道 ID 的演示,其中我使用 curl 从 url 读取 xml 数据。

$channel_id = 'XXXXXXXX'; // put the channel id here

//using curl
$url = 'https://www.youtube.com/feeds/videos.xml?channel_id='.$channel_id.'&orderby=published';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
//curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
$response  = curl_exec($ch);
curl_close($ch);

$response=simplexml_load_string($response);
$json = json_encode($response);
$youtube= json_decode($json, true);

$count = 0;
if(isset($youtube['entry']['0']) && $youtube['entry']['0']!=array())
{
    foreach ($youtube['entry'] as $k => $v) {
        $yt_vids[$count]['id'] = str_replace('http://www.youtube.com/watch?v=', '', $v['link']['@attributes']['href']);
        $yt_vids[$count]['title'] = $v['title'];
        $count++;
    }
}
else
{
    $yt_vids[$count]['id']=str_replace('http://www.youtube.com/watch?v=', '', $youtube['entry']['link']['@attributes']['href']);
    $yt_vids[$count]['title']=$youtube['title'];
}
echo "<pre>";
print_r($yt_vids);
于 2016-09-23T10:44:02.087 回答