搜尋
首頁後端開發PHP問題php中xml轉換json問題

php中xml轉換json問題

Jul 23, 2020 am 09:47 AM
jsonphpxml

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

可以在命令列中執行該程序,輸入以下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 實作

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

(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"
 }
 ]}
}

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

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

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
酸與基本數據庫:差異和何時使用。酸與基本數據庫:差異和何時使用。Mar 26, 2025 pm 04:19 PM

本文比較了酸和基本數據庫模型,詳細介紹了它們的特徵和適當的用例。酸優先確定數據完整性和一致性,適合財務和電子商務應用程序,而基礎則側重於可用性和

PHP安全文件上傳:防止與文件相關的漏洞。PHP安全文件上傳:防止與文件相關的漏洞。Mar 26, 2025 pm 04:18 PM

本文討論了確保PHP文件上傳的確保,以防止諸如代碼注入之類的漏洞。它專注於文件類型驗證,安全存儲和錯誤處理以增強應用程序安全性。

PHP輸入驗證:最佳實踐。PHP輸入驗證:最佳實踐。Mar 26, 2025 pm 04:17 PM

文章討論了PHP輸入驗證以增強安全性的最佳實踐,重點是使用內置功能,白名單方法和服務器端驗證等技術。

PHP API率限制:實施策略。PHP API率限制:實施策略。Mar 26, 2025 pm 04:16 PM

本文討論了在PHP中實施API速率限制的策略,包括諸如令牌桶和漏水桶等算法,以及使用Symfony/Rate-limimiter之類的庫。它還涵蓋監視,動態調整速率限制和手

php密碼哈希:password_hash和password_verify。php密碼哈希:password_hash和password_verify。Mar 26, 2025 pm 04:15 PM

本文討論了使用password_hash和pyspasswify在PHP中使用密碼的好處。主要論點是,這些功能通過自動鹽,強大的哈希算法和SECH來增強密碼保護

OWASP前10 php:描述並減輕常見漏洞。OWASP前10 php:描述並減輕常見漏洞。Mar 26, 2025 pm 04:13 PM

本文討論了OWASP在PHP和緩解策略中的十大漏洞。關鍵問題包括注射,驗證損壞和XSS,並提供用於監視和保護PHP應用程序的推薦工具。

PHP XSS預防:如何預防XSS。PHP XSS預防:如何預防XSS。Mar 26, 2025 pm 04:12 PM

本文討論了防止PHP中XSS攻擊的策略,專注於輸入消毒,輸出編碼以及使用安全增強的庫和框架。

PHP接口與抽像類:何時使用。PHP接口與抽像類:何時使用。Mar 26, 2025 pm 04:11 PM

本文討論了PHP中接口和抽像類的使用,重點是何時使用。界面定義了無實施的合同,適用於無關類和多重繼承。摘要類提供常見功能

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

SecLists

SecLists

SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中