ホームページ  >  記事  >  バックエンド開発  >  PHPでXMLを配列に変換する方法

PHPでXMLを配列に変換する方法

高洛峰
高洛峰オリジナル
2016-12-22 15:03:171376ブラウズ

curlを使用してxmlデータを取得する場合
xml=simplexmlloadstring(data);
data[′tk′]=jsondecode(jsonencode(xml),TRUE);
URLデータを直接取得する場合
xml=simplexmlloadfile(data ) ;
data['tk']=jsondecode(jsonencode(xml),TRUE);
まず、simplexml オブジェクトを json に変換し、次に json を配列に変換します。

コード:

<?php
$string = <<<XML
<?xml version=&#39;1.0&#39;?> 
<document>
 <title>Forty What?</title>
 <from>Joe</from>
 <to>Jane</to>
 <body>
 I know that&#39;s the answer -- but what&#39;s the question?
 </body>
</document>
XML;
 
$xml=simplexml_load_string($string);
$data = json_decode(json_encode($xml),TRUE);
var_dump( $xml );
var_dump( $data );
object(SimpleXMLElement)[1]
 public &#39;title&#39; => string &#39;Forty What?&#39; (length=11)
 public &#39;from&#39; => string &#39;Joe&#39; (length=3)
 public &#39;to&#39; => string &#39;Jane&#39; (length=4)
 public &#39;body&#39; => string &#39;
 I know that&#39;s the answer -- but what&#39;s the question?
 &#39; (length=57)
array
 &#39;title&#39; => string &#39;Forty What?&#39; (length=11)
 &#39;from&#39; => string &#39;Joe&#39; (length=3)
 &#39;to&#39; => string &#39;Jane&#39; (length=4)
 &#39;body&#39; => string &#39;
 I know that&#39;s the answer -- but what&#39;s the question?
 &#39; (length=57)

上記がこの記事の全内容です。皆さんの学習に役立つことを願っています。


PHP が XML を配列に変換する方法に関連するその他の記事については、PHP 中国語 Web サイトに注目してください。


声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。