ホームページ  >  記事  >  バックエンド開発  >  PHPでのXMLからJSONへの変換に関する問題

PHPでのXMLからJSONへの変換に関する問題

coldplay.xixi
coldplay.xixiオリジナル
2020-07-23 09:47:022970ブラウズ

php で xml を json に変換する方法: まず、SimpleXMLElement を使用して XML コンテンツを適切な PHP データ型に変換し、次に PHP データを [Services_JSON] エンコーダーに提供し、最後に最終的な JSON 形式の出力が可能です。

PHPでのXMLからJSONへの変換に関する問題

php で xml を json に変換する方法:

XML を JSON に変換する必要があるアプリケーションがますます増えています。このタイプの変換を実行するための Web ベースのサービスがいくつか登場しています。 IBM T.J. Watson Research Center は、PHP を使用してこの変換を実行するための特殊な方法を開発しました。このメソッドは、XML 文字列データを入力として受け取り、それを JSON 形式のデータ出力に変換します。この PHP ソリューションには次の利点があります。

  • はスタンドアロン モードで実行でき、コマンド ラインから実行できます。

  • 既存のサーバー側コード成果物に含めることができます。

  • Web 上で Web サービスとして簡単にホストできます。

#XML から JSON への変換には、2 つのコア PHP 機能を使用する必要があります:

  • SimpleXMLElement

  • # # Services_JSON
  • XML データを JSON に変換するには、これら 2 つのコア PHP 機能のみが必要です。まず、SimpleXMLElement を使用して XML コンテンツを適切な PHP データ型に変換する必要があります。次に、PHP データは Services_JSON エンコーダーに供給され、最終的な JSON 形式の出力が生成されます。

関連する学習の推奨事項:
PHP プログラミングの入門から熟練度まで

PHP コードの理解

これxml2json 実装は 3 つの部分で構成されます。

    xml2json.php - この PHP クラスには 2 つの静的関数が含まれています
  • xml2json_test.php - xml2json テストの実行変換関数用ドライバー
  • test1.xml、test2.xml、test3.xml、test4.xml - 複雑さの異なる XML ファイル
  • わかりやすくするために、この記事ではコード内の詳細なコメントを省略しています。ただし、添付のソース ファイルには完全なコメントが含まれています。完全なプログラム ロジックの詳細については、添付のソース ファイルを参照してください (ダウンロードを参照)。

(1) は、使用するいくつかの定数を定義します。コードの最初の行は、Services_JSON 実装をインポートします。

(1)

xml2json.php

で定数を定義します。 <pre class="brush:php;toolbar:false">require_once &amp;#39;json/JSON.php&amp;#39;; // Internal program-specific Debug option. define (&quot;DEBUG&quot;, false); // Maximum Recursion Depth that we can allow. define (&quot;MAX_RECURSION_DEPTH_ALLOWED&quot;, 25); // An empty string define (&quot;EMPTY_STR&quot;, &quot;&quot;); // SimpleXMLElement object property name for attributes define (&quot;SIMPLE_XML_ELEMENT_OBJECT_PROPERTY_FOR_ATTRIBUTES&quot;, &quot;@attributes&quot;); // SimpleXMLElement object name. define (&quot;SIMPLE_XML_ELEMENT_PHP_CLASS&quot;, &quot;SimpleXMLElement&quot;);</pre> (2) のコード スニペットは、xml2json コンバーターのエントリ関数です。 XML データを入力として受け取り、XML 文字列を SimpleXMLElement オブジェクトに変換し、それをクラスの別の (再帰) 関数に入力として送信します。この関数は、XML 要素を PHP 連想配列に変換します。この配列は入力として Services_JSON エンコーダーに渡され、JSON 形式で出力が得られます。

(2)

xml2json.php

Services_JSON<pre class="brush:php;toolbar:false">public static function transformXmlStringToJson($xmlStringContents) { $simpleXmlElementObject = simplexml_load_string($xmlStringContents); &lt;br&gt; if ($simpleXmlElementObject == null) { return(EMPTY_STR); } &lt;br&gt; $jsonOutput = EMPTY_STR; &lt;br&gt; // Let us convert the XML structure into PHP array structure. $array1 = xml2json::convertSimpleXmlElementObjectIntoArray($simpleXmlElementObject); &lt;br&gt; if (($array1 != null) &amp;&amp; (sizeof($array1) &gt; 0)) { // Create a new instance of Services_JSON $json = new Services_JSON(); // Let us now convert it to JSON formatted data. $jsonOutput = $json-&gt;encode($array1); } // End of if (($array1 != null) &amp;&amp; (sizeof($array1) &gt; 0)) &lt;br&gt; return($jsonOutput); } // End of function transformXmlStringToJson</pre> を使用します (3) この長いコード スニペットは、コミュニティ (「参考文献」を参照)。入力 SimpleXMLElement オブジェクトを受け取り、ネストされた XML ツリーに沿って再帰的に走査します。訪問した XML 要素を PHP 連想配列に保存します。最大再帰深さは、4 で定義した定数を変更することで変更できます。

(3)

xml2json.php

<pre class="brush:php;toolbar:false">public static function convertSimpleXmlElementObjectIntoArray($simpleXmlElementObject, &amp;$recursionDepth=0) { // Keep an eye on how deeply we are involved in recursion. &lt;br&gt; if ($recursionDepth &gt; MAX_RECURSION_DEPTH_ALLOWED) { // Fatal error. Exit now. return(null); } &lt;br&gt; if ($recursionDepth == 0) { if (get_class($simpleXmlElementObject) != SIMPLE_XML_ELEMENT_PHP_CLASS) { // If the external caller doesn&amp;#39;t call this function initially // with a SimpleXMLElement object, return now. return(null); } else { // Store the original SimpleXmlElementObject sent by the caller. // We will need it at the very end when we return from here for good. $callerProvidedSimpleXmlElementObject = $simpleXmlElementObject; } } // End of if ($recursionDepth == 0) { &lt;br&gt; if (get_class($simpleXmlElementObject) == SIMPLE_XML_ELEMENT_PHP_CLASS) { // Get a copy of the simpleXmlElementObject $copyOfsimpleXmlElementObject = $simpleXmlElementObject; // Get the object variables in the SimpleXmlElement object for us to iterate. $simpleXmlElementObject = get_object_vars($simpleXmlElementObject); } &lt;br&gt; // It needs to be an array of object variables. if (is_array($simpleXmlElementObject)) { // Is the array size 0? Then, we reached the rare CDATA text if any. if (count($simpleXmlElementObject) &lt;= 0) { // Let us return the lonely CDATA. It could even be // an empty element or just filled with whitespaces. return (trim(strval($copyOfsimpleXmlElementObject))); } &lt;br&gt; // Let us walk through the child elements now. foreach($simpleXmlElementObject as $key=&gt;$value) { // When this block of code is commented, XML attributes will be // added to the result array. // Uncomment the following block of code if XML attributes are // NOT required to be returned as part of the result array. /* if($key == SIMPLE_XML_ELEMENT_OBJECT_PROPERTY_FOR_ATTRIBUTES) { continue; } */ &lt;br&gt; // Let us recursively process the current element we just visited. // Increase the recursion depth by one. $recursionDepth++; $resultArray[$key] = xml2json::convertSimpleXmlElementObjectIntoArray($value, $recursionDepth); &lt;br&gt; // Decrease the recursion depth by one. $recursionDepth--; } // End of foreach($simpleXmlElementObject as $key=&gt;$value) { &lt;br&gt; if ($recursionDepth == 0) { // That is it. We are heading to the exit now. // Set the XML root element name as the root [top-level] key of // the associative array that we are going to return to the caller of this // recursive function. $tempArray = $resultArray; $resultArray = array(); $resultArray[$callerProvidedSimpleXmlElementObject-&gt;getName()] = $tempArray; } &lt;br&gt; return ($resultArray); } else { // We are now looking at either the XML attribute text or // the text between the XML tags. return (trim(strval($simpleXmlElementObject))); } // End of else } // End of function convertSimpleXmlElementObjectIntoArray.</pre>の変換ロジック XML ツリーを正常に走査した後、この関数は PHP 連想配列を使用してすべての XML 要素 (ルート要素とすべての子要素)。複雑な XML ドキュメントの場合、結果として得られる PHP 配列も同様に複雑になります。 PHP 配列が構築されると、Services_JSON エンコーダーはそれを JSON 形式のデータに簡単に変換します。再帰ロジックを理解するには、アーカイブされたソース ファイルを参照してください。

xml2json テスト ドライバーの実装

(4) のコード スニペットは、xml2json コンバーター ロジックを実行するテスト ドライバーです。

(4)

xml2json_test.php

<pre class="brush:php;toolbar:false">&lt;?php require_once(&quot;xml2json.php&quot;); &lt;br&gt; // Filename from where XML contents are to be read. $testXmlFile = &quot;&quot;; &lt;br&gt; // Read the filename from the command line. if ($argc &lt;= 1) { print(&quot;Please provide the XML filename as a command-line argument:\n&quot;); print(&quot;\tphp -f xml2json_test.php test1.xml\n&quot;); return; } else { $testXmlFile = $argv[1]; } &lt;br&gt; //Read the XML contents from the input file. file_exists($testXmlFile) or die(&amp;#39;Could not find file &amp;#39; . $testXmlFile); $xmlStringContents = file_get_contents($testXmlFile); &lt;br&gt; $jsonContents = &quot;&quot;; // Convert it to JSON now. // xml2json simply takes a String containing XML contents as input. $jsonContents = xml2json::transformXmlStringToJson($xmlStringContents); &lt;br&gt; echo(&quot;JSON formatted output generated by xml2json:\n\n&quot;); echo($jsonContents); ?&gt;</pre>コマンド ラインでプログラムを実行するには、コマンド ライン パラメーターとして次の XML ファイル名を入力します。

php -f xml2json_test.php test2.xml

コマンド ラインから実行すると、プログラムは XML コンテンツをファイルから文字列変数に読み取ります。次に、xml2json クラスの静的関数を呼び出して、結果を JSON 形式で取得します。コマンド ラインからプログラムを実行するだけでなく、このソース ファイル内のロジックを変更して、Simple Object Access Protocol (SOAP) または Representational State Transfer (REST) アクセス プロトコルを使用してリモート呼び出し可能として xml2json コンバーターを公開することもできます。ウェブサービス。必要に応じて、このリモート呼び出しは、いくつかの変更を加えるだけで PHP に実装できます。

(5) は、この記事で提供される 4 つのテスト XML ファイルのうちの 1 つを示しています。これらは、xml2json 実装のテストに使用されます。複雑さはさまざまです。これらのファイルは、コマンド ライン引数としてテスト ドライバー xml2json_test.php に渡すことができます。

(5) test2.xml を使用して xml2json 実装をテストする

<?xml version="1.0" encoding="UTF-8"?>
<books>
    <book id="1">
        <title>Code Generation in Action</title>
        <author><first>Jack</first><last>Herrington</last></author>
        <publisher>Manning</publisher>
    </book>
<br>
    <book id="2">
        <title>PHP Hacks</title>
        <author><first>Jack</first><last>Herrington</last></author>
        <publisher>O&#39;Reilly</publisher>
    </book>
<br>
    <book id="3">
        <title>Podcasting Hacks</title>
        <author><first>Jack</first><last>Herrington</last></author>
        <publisher>O&#39;Reilly</publisher>
    </book>
</books>

(6) に示されているコード スニペットは、test2.xml をテスト ドライバー xml2json_test.php のコマンド ライン パラメーターとして使用する場合です。 JSON形式の結果。

(6) test2.xml

のJSON形式の結果

{
 "books" : {
 "book" : [ {
 "@attributes" : {
 "id" : "1"
 }, 
 "title" : "Code Generation in Action", 
 "author" : {
 "first" : "Jack", "last" : "Herrington"
 }, 
 "publisher" : "Manning"
 }, {
 "@attributes" : {
 "id" : "2"
 }, 
 "title" : "PHP Hacks", "author" : {
 "first" : "Jack", "last" : "Herrington"
 }, 
 "publisher" : "O&#39;Reilly"
 }, {
 "@attributes" : {
 "id" : "3"
 }, 
 "title" : "Podcasting Hacks", "author" : {
 "first" : "Jack", "last" : "Herrington"
 }, 
 "publisher" : "O&#39;Reilly"
 }
 ]}
}

请注意,463aef0d2da08708f472268a99530dbe 元素的 XML 属性 id 作为 "@attributes" 对象的属性被保存在 JSON 数据中,463aef0d2da08708f472268a99530dbe 元素作为对象数组被保存在 JSON 数据中。JSON 输出易于在 JavaScript 代码中使用 eval 语句进行处理。

以上がPHPでのXMLからJSONへの変換に関する問題の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

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