>  기사  >  백엔드 개발  >  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으로 변환해야 하는 애플리케이션이 점점 더 많아지고 있습니다. 이러한 유형의 변환을 수행하기 위해 여러 웹 기반 서비스가 등장했습니다. IBM T.J. Watson 연구 센터는 PHP를 사용하여 이러한 변환을 수행하는 특별한 방법을 개발했습니다. 이 방법은 XML 문자열 데이터를 입력으로 사용하고 이를 JSON 형식의 데이터 출력으로 변환합니다. 이 PHP 솔루션에는 다음과 같은 장점이 있습니다.

  • 독립형 모드에서 실행하고 명령줄에서 실행할 수 있습니다.

  • 기존 서버 측 코드 아티팩트에 포함될 수 있습니다.

  • 웹에서 웹 서비스로 쉽게 호스팅됩니다.

XML을 JSON으로 변환하려면 다음 두 가지 핵심 PHP 기능을 사용해야 합니다.

  • SimpleXMLElement

  • Services_JSON

XML 데이터를 JSON으로 변환하려면 이 두 가지 핵심 PHP 기능만 필요합니다. 먼저 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에 상수를 정의합니다. 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); 
<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

(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.
<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.

成功遍历 XML 树之后,该函数就用 PHP 关联数组转换和存储了所有的 XML 元素(根元素和所有的孩子元素)。复杂的 XML 文档,得到的 PHP 数组也同样复杂。一旦 PHP 数组构造完成,Services_JSON 编码器就很容易将其转化成 JSON 格式的数据了。要了解其中的递归逻辑,请参阅存档的源文件。

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

(2)의 코드 조각은 xml2json 변환기의 입력 기능입니다. XML 데이터를 입력으로 받고, XML 문자열을 SimpleXMLElement 객체로 변환한 다음, 이를 클래스의 다른(재귀) 함수에 입력으로 보냅니다. 이 함수는 XML 요소를 PHP 연관 배열로 변환합니다. 그런 다음 이 배열은 Services_JSON 인코더에 입력으로 전달되어 JSON 형식으로 출력을 제공합니다.

(2) xml2json.php에서 Services_JSON 사용

php -f xml2json_test.php test2.xml

(3) 이 긴 코드 조각은 PHP 오픈 소스 커뮤니티(참고자료 참조)에서 재귀 기술을 채택했습니다. 제안했다. 입력 SimpleXMLElement 객체를 수신하고 중첩된 XML 트리를 따라 재귀적으로 탐색합니다. 방문한 XML 요소를 PHP 연관 배열에 저장합니다. 최대 재귀 깊이는 4에서 정의한 상수를 수정하여 변경할 수 있습니다.

(3) xml2json.php의 변환 논리

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

XML 트리를 성공적으로 탐색한 후 이 함수는 PHP 연관 배열을 사용하여 모든 XML 요소(루트 요소 및 모든 하위 요소)를 변환하고 저장합니다. 복잡한 XML 문서의 경우 결과 PHP 배열도 똑같이 복잡합니다. PHP 배열이 구성되면 Services_JSON 인코더는 이를 JSON 형식 데이터로 쉽게 변환합니다. 재귀 논리를 이해하려면 보관된 소스 파일을 참조하세요.

xml2json 테스트 드라이버 구현

🎜🎜 (4)의 코드 조각은 xml2json 변환기 논리를 실행하는 테스트 드라이버입니다. 🎜🎜(4) xml2json_test.php🎜
{
 "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"
 }
 ]}
}
🎜명령줄에서 프로그램을 실행할 수 있으며, 다음 XML 파일 이름을 명령줄 매개변수로 입력하세요. 🎜rrreee🎜명령줄에서 실행할 때, 프로그램은 파일의 XML 내용을 문자열 변수로 읽습니다. 그런 다음 xml2json 클래스의 정적 함수를 호출하여 결과를 JSON 형식으로 가져옵니다. 명령줄에서 프로그램을 실행하는 것 외에도 이 소스 파일의 논리를 수정하여 SOAP(Simple Object Access Protocol) 또는 REST(Representational State Transfer) 액세스 프로토콜을 사용하여 xml2json 변환기를 원격 호출 가능 항목으로 노출할 수 있습니다. 웹 서비스. 필요한 경우 몇 가지 수정만으로 이 원격 호출을 PHP에서 구현할 수 있습니다. 🎜🎜(5)는 xml2json 구현을 테스트하기 위해 이 기사와 함께 제공된 4개의 테스트 XML 파일 중 하나를 보여줍니다. 복잡성이 다양합니다. 이러한 파일은 테스트 드라이버 xml2json_test.php에 명령줄 인수로 전달될 수 있습니다. 🎜🎜(5) test2.xml을 사용하여 xml2json 구현 테스트 🎜rrreee🎜(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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.