本文操作环境:Windows7系统、PHP7.1版、DELL G3电脑
php怎么读取远程xml文件并转化为数组?
PHP读取远程xml文件并转化为数组:
远程文件如下:http://api.wycq.521g.com/game/mrt_consume/xyg ,打开是一个xml文件,内容是一个游戏的充值排名和不同名次奖励信息,需要取出前十名的信息和奖励信息用于展示,
实现代码如下:
public function index()
{
$url = "http://api.wycq.521g.com/game/mrt_consume/xyg";
$contentxml = simplexml_load_file($url); //取得xml对象,需要转化为数组
$ranks = array();
for($i=0;$i<=9;$i++)
{
$temp_player = (array)$contentxml->ranking->player[$i]; //循环把条排名数据对象转化为数组
$ranks[$i+1] = $temp_player['@attributes']; //取出数组中相应的属性值
}
$awards = array();
for($i=0;$i<=4;$i++)
{
$awards[$i] = (array)$contentxml->awards->award[$i]; //循环把奖励数据对象转化为数组
}
$res_awards = array();
foreach($awards as $k=>$v)
{
$res_awards[$k]["caption"] = $v['@attributes']["caption"]; //进一步处理把数组处理干净
$res_awards[$k]["items"] = array();
foreach((array)$v["items"] as $m =>$n)
{
$res_awards[$k]["items"] = $n;
}
}
for($j=0;$j<=4;$j++)
{
foreach($res_awards[$j]["items"] as $p=>$q)
{
$temp_q = (array)$q;
$res_awards[$j]["items"][$p] = $temp_q['@attributes'];
}
}
$this->_data["ranks"] = $ranks;
$this->_data["res_awards"]= $res_awards;
$this->load->view('hd/wymingrentang/wymingrentang', $this->_data); //指定view页输出数据
}