在 PHP 中转换 XML 到 JSON
    
    
            Minahil Noor
    2021年2月25日
    
    PHP
    PHP XML
    PHP JSON
    
本文将介绍在 PHP 中把 XML 字符串转换为 JSON 的方法。
在 PHP 中使用 simplexml_load_string() 和 json_encode() 函数把一个 XML 字符串转换为 JSON
    
我们将使用两个函数在 PHP 中把 XML 字符串转换为 JSON,因为没有专门的函数可以直接转换。这两个函数是 simplexml_load_string() 和 json_encode()。使用这些函数将 XML 字符串转换为 JSON 的正确语法如下。
simplexml_load_string($data, $class_name, $options, $ns, $is_prefix);
simplexml_load_string() 函数接受五个参数。它的详细参数如下。
| 变量 | 说明 | |
|---|---|---|
$data | 
强制 | 格式正确的 XML 字符串。 | 
$class_name | 
可选 | 我们使用这个可选的参数,这样 simplexml_load_string() 将返回一个指定类的对象。这个类应该扩展 SimpleXMLElement 类。 | 
options | 
可选 | 我们还可以使用 options 参数来指定额外的 Libxml 参数。 | 
ns | 
可选 | 命名空间前缀或 URI。 | 
$is_prefix | 
可选 | 如果 $ns 是前缀,则设置为 true,如果是 URI,则设置为 false。其默认值为 false。 | 
该函数返回类 SimpleXMLElement 的对象,其中包含 XML 字符串中的数据,如果失败则返回 False。
json_encode($value, $flags, $depth);
json_encode() 函数有三个参数。其参数的详细情况如下。
| 变量 | 说明 | |
|---|---|---|
$value | 
强制 | 正在编码的值。 | 
$flags | 
可选 | 由 JSON_FORCE_OBJECT、JSON_HEX_QUOT、JSON_HEX_TAG、JSON_HEX_AMP、JSON_HEX_APOS、JSON_INVALID_UTF8_IGNORE、JSON_INVALID_UTF8_SUBSTITUTE、JSON_NUMERIC_CHECK 组成的位屏蔽。JSON_PARTIAL_OUTPUT_ON_ERROR、JSON_PRESERVE_ZERO_FRACTION、JSON_PRETTY_PRINT、JSON_UNESCAPED_LINE_TERMINATORS、JSON_UNESCAPED_SLASHES、JSON_UNESCAPED_UNICODE、JSON_THROW_ON_ERROR。 | 
$depth | 
可选 | 最大深度。应大于零。 | 
该函数返回 JSON 值。下面的程序显示了我们在 PHP 中使用 simplexml_load_string() 和 json_encode() 函数将 XML 字符串转换为 JSON 的方法。
<?php   
$xml_string =  <<<XML
<?xml version='1.0' standalone='yes'?>
<movies>
 <movie>
  <title>PHP: Behind the Parser</title>
  <characters>
   <character>
    <name>Ms. Coder</name>
    <actor>Onlivia Actora</actor>
   </character>
   <character>
    <name>Mr. Coder</name>
    <actor>El ActÓr</actor>
   </character>
  </characters>
  <plot>
   So, this language. It is like, a programming language. Or is it a
   scripting language? All is revealed in this thrilling horror spoof
   of a documentary.
  </plot>
  <great-lines>
   <line>PHP solves all my web problems</line>
  </great-lines>
  <rating type="thumbs">7</rating>
  <rating type="stars">5</rating>
 </movie>
</movies>
XML;
$xml = simplexml_load_string($xml_string);
$json = json_encode($xml); // convert the XML string to JSON
var_dump($json);
?>
输出:
string(415) "{"movie":{"title":"PHP: Behind the Parser","characters":{"character":[{"name":"Ms. Coder","actor":"Onlivia Actora"},{"name":"Mr. Coder","actor":"El Act\u00d3r"}]},"plot":"\n   So, this language. It is like, a programming language. Or is it a\n   scripting language? All is revealed in this thrilling horror spoof\n   of a documentary.\n  ","great-lines":{"line":"PHP solves all my web problems"},"rating":["7","5"]}}"
        Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe