程序简单步骤"使用curl检索XML URl数据,得到XML数组 结果,然后XML数组到简单的PHP数组,输出如下。
Array ( [channel] => SimpleXMLElement Object ( [title] => Mobile01 本站新聞
[link] => (link##) [description] => Mobile01 本站新聞 [pubDate] => Fri, 22
Sep 2017 09:58:02 +0800 [item] => Array ( [0] => SimpleXMLElement Object (
[title] => HP Envy 13-ad050TX 輕薄、獨顯、長效續航力 [link] => (link##)
[pubDate] => Fri, 22 Sep 2017 09:52:41 +0800 [description] =>
SimpleXMLElement Object ( ) [category] => HP ) [1] => SimpleXMLElement
Object ( [title] => 雙倍震撼 RealShow TWIN 高解析雙體藍牙喇叭 [link] =>
(link##) [pubDate] => Fri, 22 Sep 2017 09:43:45 +0800 [description] =>
SimpleXMLElement Object ( ) [category] => 行動影音 )
现在我只想" item"从数组而不是通道..当我尝试foreach循环时,我得到的频道不是" item"使用下面给出的代码。
$post="";
$agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US;
rv:1.8.1.1)
Gecko/20061204 Firefox/2.0.0.1';
$url= "https://www.mobile01.com/rss/news.xml";
$ch = curl_init();
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:
application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
$result = curl_exec($ch);
curl_close($ch);
$xml = new SimpleXMLElement($result);
$array = array();
foreach($xml as $k => $v) {
$array[$k] = $v;
}
$i=0;
print_r($array);
foreach ($array->item as $key=>$entry) {
echo "title===>". $title =$entry['title'];
echo "link===>".$link =$entry['link'];
echo "title111===>".$title11 = $entry -> title;
echo "description===>".$description = $entry -> description;
尝试使用不同方面的代码时,出错了
Fatal error:
require_once(): Failed opening required 'lib/class.XmlToArray.php'
(include_path='.:/usr/lib/php:/usr/local/lib/php')
程序简单步骤"使用curl检索XML URl数据,得到XML数组 结果,然后将XML数组转换为简单的PHP数组,得到如下输出。程序简单步骤"使用curl检索XML URl数据,得到XML数组 结果,然后XML数组到简单的PHP数组,输出如下。
答案 0 :(得分:0)
您不需要包含任何其他库,只需坚持使用SimpleXML即可。一旦获得正确的数据,就可以像......一样处理它。
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$post="";
$agent = 'spider';
$url= "https://www.mobile01.com/rss/news.xml";
$ch = curl_init();
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_HEADER, false);
$result = curl_exec($ch);
curl_close($ch);
$xml = new SimpleXMLElement($result);
foreach ($xml->channel->item as $key=>$entry) {
echo "title=>".$entry -> title.PHP_EOL;
echo "description=>".$entry -> description.PHP_EOL;
}