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 服務。
XML 到JSON 的轉換需要用到兩種PHP 核心特性:
SimpleXMLElement
Services_JSON
只需要這兩種PHP 核心特性,就可以將任何XML 資料轉換成JSON。首先,需要使用 SimpleXMLElement 將 XML 內容轉換成適當的 PHP 資料類型。然後將 PHP 資料提供給 Services_JSON 編碼器,後者再產生最終的 JSON 格式的輸出。
相關學習推薦:PHP程式設計從入門到精通
#理解PHP 程式碼
這個xml2json 實作包含三個部分:
xml2json.php —— 這個PHP 類別包含兩個靜態函數
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");
xml2json.php 中的
Services_JSON
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
xml2json.php 中的轉換邏輯
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'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.
xml2json 測試驅動程式的實作
(4)中的程式碼片段是一個用於執行 xml2json 轉換器邏輯的測試驅動程式。 (4)xml2json_test.php
<?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('Could not find file ' . $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); ?>
php -f xml2json_test.php test2.xml
<?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>
{ "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中文網其他相關文章!