php で xml を json に変換する方法: まず、SimpleXMLElement を使用して XML コンテンツを適切な PHP データ型に変換し、次に PHP データを [Services_JSON] エンコーダーに提供し、最後に最終的な JSON 形式の出力が可能です。
php で xml を json に変換する方法:
XML を JSON に変換する必要があるアプリケーションがますます増えています。このタイプの変換を実行するための Web ベースのサービスがいくつか登場しています。 IBM T.J. Watson Research Center は、PHP を使用してこの変換を実行するための特殊な方法を開発しました。このメソッドは、XML 文字列データを入力として受け取り、それを JSON 形式のデータ出力に変換します。この PHP ソリューションには次の利点があります。
はスタンドアロン モードで実行でき、コマンド ラインから実行できます。
既存のサーバー側コード成果物に含めることができます。
Web 上で Web サービスとして簡単にホストできます。
- 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 &#39;json/JSON.php&#39;;
// Internal program-specific Debug option.
define ("DEBUG", false);
// Maximum Recursion Depth that we can allow.
define ("MAX_RECURSION_DEPTH_ALLOWED", 25);
// An empty string
define ("EMPTY_STR", "");
// SimpleXMLElement object property name for attributes
define ("SIMPLE_XML_ELEMENT_OBJECT_PROPERTY_FOR_ATTRIBUTES", "@attributes");
// SimpleXMLElement object name.
define ("SIMPLE_XML_ELEMENT_PHP_CLASS", "SimpleXMLElement");</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);
<br>
if ($simpleXmlElementObject == null) {
return(EMPTY_STR);
}
<br>
$jsonOutput = EMPTY_STR;
<br>
// Let us convert the XML structure into PHP array structure.
$array1 = xml2json::convertSimpleXmlElementObjectIntoArray($simpleXmlElementObject);
<br>
if (($array1 != null) && (sizeof($array1) > 0)) {
// Create a new instance of Services_JSON
$json = new Services_JSON();
// Let us now convert it to JSON formatted data.
$jsonOutput = $json->encode($array1);
} // End of if (($array1 != null) && (sizeof($array1) > 0))
<br>
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,
&$recursionDepth=0) {
// Keep an eye on how deeply we are involved in recursion.
<br>
if ($recursionDepth > MAX_RECURSION_DEPTH_ALLOWED) {
// Fatal error. Exit now.
return(null);
}
<br>
if ($recursionDepth == 0) {
if (get_class($simpleXmlElementObject) != SIMPLE_XML_ELEMENT_PHP_CLASS) {
// If the external caller doesn&#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) {
<br>
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);
}
<br>
// 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) <= 0) {
// Let us return the lonely CDATA. It could even be
// an empty element or just filled with whitespaces.
return (trim(strval($copyOfsimpleXmlElementObject)));
}
<br>
// Let us walk through the child elements now.
foreach($simpleXmlElementObject as $key=>$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;
}
*/
<br>
// Let us recursively process the current element we just visited.
// Increase the recursion depth by one.
$recursionDepth++;
$resultArray[$key] =
xml2json::convertSimpleXmlElementObjectIntoArray($value, $recursionDepth);
<br>
// Decrease the recursion depth by one.
$recursionDepth--;
} // End of foreach($simpleXmlElementObject as $key=>$value) {
<br>
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->getName()] = $tempArray;
}
<br>
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 形式のデータに簡単に変換します。再帰ロジックを理解するには、アーカイブされたソース ファイルを参照してください。
(4) のコード スニペットは、xml2json コンバーター ロジックを実行するテスト ドライバーです。
(4)
xml2json_test.php<pre class='brush:php;toolbar:false;'><?php
require_once("xml2json.php");
<br>
// Filename from where XML contents are to be read.
$testXmlFile = "";
<br>
// Read the filename from the command line.
if ($argc <= 1) {
print("Please provide the XML filename as a command-line argument:\n");
print("\tphp -f xml2json_test.php test1.xml\n");
return;
} else {
$testXmlFile = $argv[1];
}
<br>
//Read the XML contents from the input file.
file_exists($testXmlFile) or die(&#39;Could not find file &#39; . $testXmlFile);
$xmlStringContents = file_get_contents($testXmlFile);
<br>
$jsonContents = "";
// Convert it to JSON now.
// xml2json simply takes a String containing XML contents as input.
$jsonContents = xml2json::transformXmlStringToJson($xmlStringContents);
<br>
echo("JSON formatted output generated by xml2json:\n\n");
echo($jsonContents);
?></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'Reilly</publisher> </book> <br> <book id="3"> <title>Podcasting Hacks</title> <author><first>Jack</first><last>Herrington</last></author> <publisher>O'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'Reilly" }, { "@attributes" : { "id" : "3" }, "title" : "Podcasting Hacks", "author" : { "first" : "Jack", "last" : "Herrington" }, "publisher" : "O'Reilly" } ]} }
请注意,
以上がPHPでのXMLからJSONへの変換に関する問題の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

この記事では、酸とベースのデータベースモデルを比較し、その特性と適切なユースケースを詳述しています。酸は、財務およびeコマースアプリケーションに適したデータの整合性と一貫性を優先し、ベースは可用性に焦点を当て、

この記事では、コードインジェクションのような脆弱性を防ぐために、PHPファイルのアップロードを確保することについて説明します。ファイルタイプの検証、セキュアストレージ、およびアプリケーションセキュリティを強化するエラー処理に焦点を当てています。

記事では、組み込み関数、ホワイトリストアプローチ、サーバー側の検証などの手法に焦点を当てたセキュリティを強化するためのPHP入力検証のベストプラクティスについて説明します。

この記事では、Token BucketやLeaky BucketなどのアルゴリズムやSymfony/Rate-Limiterなどのライブラリを使用するなど、PHPでAPIレート制限を実装するための戦略について説明します。また、監視、動的に調整されたレートの制限、および手をカバーします

この記事では、パスワードを保護するためにPHPでpassword_hashとpassword_verifyを使用することの利点について説明します。主な議論は、これらの関数が自動塩の生成、強力なハッシュアルゴリズム、およびSecurを通じてパスワード保護を強化するということです

この記事では、PHPおよび緩和戦略におけるOWASPトップ10の脆弱性について説明します。重要な問題には、PHPアプリケーションを監視および保護するための推奨ツールを備えたインジェクション、認証の壊れ、XSSが含まれます。

この記事では、PHPでのXSS攻撃を防ぐための戦略について説明し、入力の消毒、出力エンコード、セキュリティを向上させるライブラリとフレームワークの使用に焦点を当てています。

この記事では、PHPでのインターフェイスと抽象クラスの使用について説明し、それぞれをいつ使用するかに焦点を当てています。インターフェイスは、無関係なクラスや複数の継承に適した、実装なしで契約を定義します。抽象クラスは共通の機能を提供します


ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

AI Hentai Generator
AIヘンタイを無料で生成します。

人気の記事

ホットツール

EditPlus 中国語クラック版
サイズが小さく、構文の強調表示、コード プロンプト機能はサポートされていません

SublimeText3 Linux 新バージョン
SublimeText3 Linux 最新バージョン

WebStorm Mac版
便利なJavaScript開発ツール

ゼンドスタジオ 13.0.1
強力な PHP 統合開発環境

AtomエディタMac版ダウンロード
最も人気のあるオープンソースエディター
