Home  >  Article  >  Backend Development  >  How to read remote xml file in php and convert it into array

How to read remote xml file in php and convert it into array

藏色散人
藏色散人Original
2021-10-27 09:33:481809browse

How to read remote xml files in php and convert them into arrays: 1. Create a PHP sample file; 2. Obtain the xml object through "simplexml_load_file"; 3. Loop to convert the data object into an array.

How to read remote xml file in php and convert it into array

The operating environment of this article: Windows7 system, PHP7.1 version, DELL G3 computer

How to read remote php xml file and convert it to array?

PHP reads the remote xml file and converts it into an array:

The remote file is as follows: http://api.wycq.521g.com/game/ mrt_consume/xyg, opens an xml file, the content is the recharge ranking of a game and the reward information for different rankings. The top ten information and reward information need to be taken out for display,

The implementation code is as follows:

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页输出数据
    }

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to read remote xml file in php and convert it into array. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn