最近在接入渠道的時候遇到接口返回是xml數據.現在接口數據返回json數據格式比較常見.
如何獲取xml里面真正數據? 對象結果集合單個值的強制轉換處理.(直接代碼說明)
demo示例: 創建xml文件:test.xml,存放在和讀取的php文件在相同級別目錄下面.
xml文件:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <node> 3 <id>10001</id> 4 <userName>admin</userName> 5 <node> 6 <token>secretKey</token> 7 </node> 8 </node>
php文件:
1 <?php 2 $file = 'test.xml'; 3 //將XML中的數據,讀取到數組對象中 4 $xml_object=simplexml_load_file($file); 5 6 //全部對象結果集合 7 //object(SimpleXMLElement)#1 (3) { ["id"]=> string(5) "10001" ["userName"]=> string(5) "admin" ["node"]=> object(SimpleXMLElement)#2 (1) { ["token"]=> string(9) "secretKey" } } 8 var_dump($xml_object); 9 echo '<pre>'; 10 11 //$xml_object->id對象值 12 //object(SimpleXMLElement)#2 (1) {[0]=>string(5) "10001"} 13 var_dump($xml_object->id); 14 echo '<pre>'; 15 16 //$xml_object->id對象值 17 //10001 (echo強制轉換結果后獲取值,注意:實際取值還需要在處理!) 18 echo($xml_object->id); 19 echo '<pre>'; 20 21 //強制轉換字符串處理,對象單個值處理
22 //$xml_object->id對象值 23 //string(5) "10001" 24 var_dump((string)$xml_object->id); 25 echo '<pre>'; 26 27 //$xml_object->node->token對象值 28 //string(9) "secretKey" 29 var_dump((string)$xml_object->node->token);
結果打印:
通過上面的解釋,我們也可以使用另一種方法獲取xml節點值的數據問題: json_encode() 對象轉成json, json_decode() json再轉成數組 . 獲取數組直接處理數據就簡單.
demo實例:
1 <?php 2 $file = 'test.xml'; 3 //將XML中的數據,讀取到數組對象中 4 $xml_object=simplexml_load_file($file); 5 6 $xml_json=json_encode($xml_object);//對象轉成json 7 $xml_arr=json_decode($xml_json,true);//json再轉成數組 8 9 echo "<pre>"; 10 var_dump($xml_arr);
結果打印: