从XML解析-> JSON-> Php对象

时间:2019-10-03 09:34:14

标签: php json xml

我将创建php对象,以从响应xml API建立我自己的表。

我试图将API响应XML转换为Json,但无法将其转换为php对象。 PHP对我来说是新的...

class ParserMy {
        public static function jsonToDebug($jsonText = '')
    {
        $arr = json_decode($jsonText, true);
        $html = "";
        if ($arr && is_array($arr)) {
            echo "<pre>".json_encode($arr,JSON_PRETTY_PRINT)."</pre>";
          //  $html .= self::_arrayToHtmlTableRecursive($arr);
        }
        return $html;
    }



}


$url = "....url....";
$xml = simplexml_load_file($url);

$json = json_encode($xml);

echo ParserMy::jsonToDebug($json);

我想将json或xml响应转换为对象数组,但是还有更多我无法管理的属性。

此json中的示例为:

{
    "station": [
        {
            "@attributes": {
                "id": "27",
                "co": "SH",
                "co_name": "Shell",
                "lat": "",
                "lng": "",
                "name": "Shell - QE",
                "address": "",
                "street_code": "",
                "highway_id": "",
                "highway": "",
                "zip": "",
                "city": "",
                "city_name": "",
                "provincia": "",
                "fuels": "bde",
                "phone": "",
                "status": "AP",
                "neighbour_distance": "",
                "insertion_date": "2008-01-01 00:00",
                "last_updated": "2013-12-31 00:00",
                "latest_price_change": "",
                "highres": "0",
                "photos": "0",
                "tags": "",
                "user": "qe"
            },
            "reports": {
                "report": [
                    {
                        "@attributes": {
                            "price": "1.666",
                            "date": "2018-04-09 00:00:00",
                            "service": "CS",
                            "fuel": "diesel"
                        }
                    },
                    {
                        "@attributes": {
                            "price": "1.782",
                            "date": "2018-04-09 00:00:00",
                            "service": "CS",
                            "fuel": "benzina"
                        }
                    }
                ]
            }
        }

    ]
}

成为唯一的对象别名

id: 27
co: SH
co_name:    Shell
name:   Shell - QE
address:    
street_code:    
zip:    
city:   
city_name:  
provincia:  
phone:  
fuels:  bde
tags:   
lat:    
lng:    
insertion_date: 2008-01-01 00:00
last_updated:   2013-12-31 00:00
latest_price_change:    
diesel (CS) 1.666 il 2018-04-09 00:00:00 cert:
benzina (CS)    1.782 il 2018-04-09 00:00:00 cert:

谢谢

1 个答案:

答案 0 :(得分:0)

使用simplexml_load_file()解析xml时,它将返回类object的{​​{1}},其属性包含XML文档中保存的数据,如果失败,则返回FALSE。

SimpleXMLElement

您可以直接将其投射到 $phpObject = simplexml_load_file($url);

array

$array = (array) $phpObject;

json

您可以在http://ideone.com/MRMW1E此处查看工作示例