Home >Backend Development >PHP Problem >Problem with converting xml to json in php

Problem with converting xml to json in php

coldplay.xixi
coldplay.xixiOriginal
2020-07-23 09:47:023069browse

How to convert xml to json in php: First, you need to use SimpleXMLElement to convert the XML content into the appropriate PHP data type; then provide the PHP data to the [Services_JSON] encoder; and finally generate the final JSON format output. Can.

Problem with converting xml to json in php

How to convert xml to json in php:

More and more applications need to convert XML into JSON. Several web-based services have emerged to perform this type of conversion. The IBM T.J. Watson Research Center has developed a specialized method for performing this conversion using PHP. This method takes XML string data as input and converts it into JSON formatted data output. This PHP solution has the following advantages:

  • can be run in standalone mode and executed from the command line.

  • Can be included into existing server-side code artifacts.

  • Easily hosted as a web service on the web.

XML to JSON conversion requires the use of two core PHP features:

  • SimpleXMLElement

  • Services_JSON

You only need these two core PHP features to convert any XML data into JSON. First, you need to use SimpleXMLElement to convert the XML content into the appropriate PHP data type. The PHP data is then fed to the Services_JSON encoder, which in turn generates the final JSON-formatted output.

Related learning recommendations: PHP programming from entry to proficiency

Understanding PHP code

This The xml2json implementation consists of three parts:

  • xml2json.php - This PHP class includes two static functions

  • xml2json_test.php - Execute xml2json Test driver for conversion function

  • test1.xml, test2.xml, test3.xml, test4.xml - XML ​​files of different complexity

For the sake of simplicity, this article omits detailed comments in the code. However, the attached source file contains complete comments. For complete program logic details, please see the attached source files (see download).

(1) defines some constants to be used. The first line of code imports the Services_JSON implementation.

(1) Define the constants in 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");

The code snippet in (2) is the entry function of the xml2json converter. It receives XML data as input, converts the XML string into a SimpleXMLElement object, and sends it as input to another (recursive) function of the class. This function converts XML elements into PHP associative arrays. This array is then passed to the Services_JSON encoder as its input, which gives the output in JSON format.

(2) Use 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> in

xml2json.php

(3) This long code snippet uses PHP open source Recursive techniques proposed by the community (see Resources). It receives an input SimpleXMLElement object and traverses recursively along the nested XML tree. Save visited XML elements in a PHP associative array. The maximum recursion depth can be changed by modifying the constants defined in 4.

(3) Conversion logic in 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&#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.

After successfully traversing the XML tree, this function uses PHP associative arrays to convert and store all XML elements (the root element and all child elements). For complex XML documents, the resulting PHP arrays are equally complex. Once the PHP array is constructed, the Services_JSON encoder easily converts it into JSON formatted data. To understand the recursive logic, see the archived source files.

xml2json test driver implementation

The code snippet in (4) is a test driver that executes the xml2json converter logic.

(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(&#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);
?>

You can run the program in the command line, enter the following XML file name as the command line parameter:

php -f xml2json_test.php test2.xml

When executed from the command line, the program reads the XML content from the file into a string variable. Then call the static function in the xml2json class to get the result in JSON format. In addition to running the program from the command line, you can modify the logic in this source file to expose the xml2json converter as a remote callable using the Simple Object Access Protocol (SOAP) or Representational State Transfer (REST) ​​access protocols. Web services. If needed, this remote call can be implemented in PHP with just a few modifications.

(5) shows one of the four test XML files provided with this article, which are used to test the xml2json implementation. They vary in complexity. These files can be passed as command line arguments to the test driver xml2json_test.php.

(5) Use test2.xml to test xml2json implementation

<?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>

The code snippet shown in (6) is when using test2.xml as the command line parameter of the test driver xml2json_test.php Result in JSON format.

(6) JSON formatted result of test2.xml

{
 "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 语句进行处理。

The above is the detailed content of Problem with converting xml to json in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn