Maison  >  Article  >  développement back-end  >  Comment lire un fichier XML distant en php et le convertir en tableau

Comment lire un fichier XML distant en php et le convertir en tableau

藏色散人
藏色散人original
2021-10-27 09:33:481809parcourir

Comment PHP lit les fichiers XML distants et les convertit en tableaux : 1. Créez un exemple de fichier PHP ; 2. Obtenez l'objet XML via "simplexml_load_file" ; 3. Bouclez pour convertir l'objet de données en tableau.

Comment lire un fichier XML distant en php et le convertir en tableau

L'environnement d'exploitation de cet article : système Windows 7, PHP version 7.1, ordinateur DELL G3

Comment php lit-il un fichier XML distant et le convertit-il en tableau ?

PHP lit le fichier xml distant et le convertit en tableau :

Le fichier distant est le suivant : http://api.wycq.521g.com/game/mrt_consume/xyg Il s'ouvre en tant que XML. et le contenu est un jeu. Les dix principales informations et informations sur les récompenses doivent être extraites pour être affichées. Le code d'implémentation est le suivant :

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

Apprentissage recommandé : "

Tutoriel vidéo PHP

"

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn