php中xml轉換json問題

coldplay.xixi
發布: 2023-03-02 22:38:02
原創
2928 人瀏覽過

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 的轉換需要用到兩種PHP 核心特性:

  • SimpleXMLElement

  • Services_JSON

只需要這兩種PHP 核心特性,就可以將任何XML 資料轉換成JSON。首先,需要使用 SimpleXMLElement 將 XML 內容轉換成適當的 PHP 資料類型。然後將 PHP 資料提供給 Services_JSON 編碼器,後者再產生最終的 JSON 格式的輸出。

相關學習推薦:PHP程式設計從入門到精通

#理解PHP 程式碼

這個xml2json 實作包含三個部分:

  • xml2json.php —— 這個PHP 類別包含兩個靜態函數

  • ##xml2json_test.php ——執行 xml2json轉換函數的測試驅動程式

  • test1.xml、test2.xml、test3.xml、test4.xml —— 複雜程度不同的XML 檔案

為了簡化起見,本文省略了程式碼中的詳細註解。不過後面附的來源文件包含完整的註解。若要了解完全的程式邏輯細節,請參閱所附的原始檔案(請參閱下載)。

(1)定義了一些要用到的常數。第一行程式碼導入了 Services_JSON 實作。

(1)定義

xml2json.php中的常數

require_once 'json/JSON.php'; // 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");
登入後複製

(2)中的程式碼片段是 xml2json 轉換器的入口函數。它接收 XML 資料作為輸入,將 XML 字串轉換成 SimpleXMLElement 對象,然後傳送給該類別的另一個(遞歸)函數作為輸入。這個函數將 XML 元素轉換成 PHP 關聯數組。這個陣列再傳給 Services_JSON 編碼器作為其輸入,該編碼器會給出 JSON 格式的輸出。

(2)使用

xml2json.php中的Services_JSON

public static function transformXmlStringToJson($xmlStringContents) { $simpleXmlElementObject = simplexml_load_string($xmlStringContents); 
if ($simpleXmlElementObject == null) { return(EMPTY_STR); }
$jsonOutput = EMPTY_STR;
// Let us convert the XML structure into PHP array structure. $array1 = xml2json::convertSimpleXmlElementObjectIntoArray($simpleXmlElementObject);
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))
return($jsonOutput); } // End of function transformXmlStringToJson
登入後複製

(3)這段長長的程式碼片段採用了PHP 開放原始碼社區(請參閱參考資料)提出的遞歸技術。它接收輸入的 SimpleXMLElement 對象,沿著嵌套的 XML 樹遞歸遍歷。將存取過的 XML 元素保存在 PHP 關聯數組中。可以透過修改4中定義的常數來改變最大遞歸深度。

(3)

xml2json.php中的轉換邏輯

public static function convertSimpleXmlElementObjectIntoArray($simpleXmlElementObject, &$recursionDepth=0) { // Keep an eye on how deeply we are involved in recursion. 
if ($recursionDepth > MAX_RECURSION_DEPTH_ALLOWED) { // Fatal error. Exit now. return(null); }
if ($recursionDepth == 0) { if (get_class($simpleXmlElementObject) != SIMPLE_XML_ELEMENT_PHP_CLASS) { // If the external caller doesn'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) {
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); }
// 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))); }
// 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; } */
// Let us recursively process the current element we just visited. // Increase the recursion depth by one. $recursionDepth++; $resultArray[$key] = xml2json::convertSimpleXmlElementObjectIntoArray($value, $recursionDepth);
// Decrease the recursion depth by one. $recursionDepth--; } // End of foreach($simpleXmlElementObject as $key=>$value) {
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; }
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.
登入後複製

成功遍歷XML 樹之後,該函數就用PHP 關聯數組轉換和存儲了所有的XML 元素(根元素和所有的孩子元素)。複雜的 XML 文檔,得到的 PHP 數組也同樣複雜。一旦 PHP 陣列建構完成,Services_JSON 編碼器就很容易將其轉換成 JSON 格式的資料了。若要了解其中的遞歸邏輯,請參閱已存檔的來源檔案。

xml2json 測試驅動程式的實作

(4)中的程式碼片段是一個用於執行 xml2json 轉換器邏輯的測試驅動程式。

(4)

xml2json_test.php

 // Filename from where XML contents are to be read. $testXmlFile = ""; 
// 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]; }
//Read the XML contents from the input file. file_exists($testXmlFile) or die('Could not find file ' . $testXmlFile); $xmlStringContents = file_get_contents($testXmlFile);
$jsonContents = ""; // Convert it to JSON now. // xml2json simply takes a String containing XML contents as input. $jsonContents = xml2json::transformXmlStringToJson($xmlStringContents);
echo("JSON formatted output generated by xml2json:\n\n"); echo($jsonContents); ?>
登入後複製

可以在命令列中執行該程序,輸入以下XML 檔案名稱作為命令列參數:

php -f xml2json_test.php test2.xml
登入後複製

在命令列中執行的時候,程式將XML 內容從檔案讀入一個字串變數。然後呼叫 xml2json 類別中的靜態函數得到 JSON 格式的結果。除了從命令列中執行該程式之外,還可以修改這個原始檔案中的邏輯來公開xml2json 轉換器,將其作為可使用簡單物件存取協定(SOAP)或Representational State Transfer (REST) 存取協定來遠端調用的Web 服務。如果需要,在 PHP 中只要稍加修改就能實現此遠端呼叫。

(5)展示了本文提供的四個測試 XML 檔案中的一個,這些檔案用於測試 xml2json 實作。他們的複雜度各不相同。可以將這些檔案作為命令列參數傳遞給測試驅動程式 xml2json_test.php。

(5)用test2.xml 測試xml2json 實作

   Code Generation in Action JackHerrington Manning  
PHP Hacks JackHerrington O'Reilly
Podcasting Hacks JackHerrington O'Reilly
登入後複製

(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" } ]} }
登入後複製

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

以上是php中xml轉換json問題的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!