【问题标题】:Is there a way to convert an XML page to JSON automatically via PHP? [duplicate]有没有办法通过 PHP 自动将 XML 页面转换为 JSON? [复制]
【发布时间】:2012-05-18 11:31:03
【问题描述】:

可能重复:
PHP convert XML to JSON

这是我的输出 XML 示例的样子:

<item>
 <Barcode>0602527522593</Barcode>
 <albumid>1818</albumid>
 <Title>Gold</Title>
 <Country>Sweden</Country>
 <Format>CD</Format>
 <Length></Length>
 <Number_of_Discs></Number_of_Discs>
 <Type>album</Type>
 <Description></Description>
 <Band_or_Artist>Adams, Ryan</Band_or_Artist>
</item>

是否有易于使用的内置 PHP 函数或插件快速将其转换为 JSON 并输出?如果不是内置的,我应该使用哪个扩展?

【问题讨论】:

  • 既然您说此 XML 是您的输出,那么从您的源数据中生成 JSON 可能比生成 XML 然后将其转换为 JSON 更容易。数据从何而来?

标签: php javascript xml json


【解决方案1】:

作为在客户端执行此操作的替代方法是来自 fyneworks 的 XML to JSON plugin

【讨论】:

    【解决方案2】:

    有很多。这是来自 IBM 的一个:http://www.ibm.com/developerworks/xml/library/x-xml2jsonphp/

    【讨论】:

      【解决方案3】:

      您可以使用 SimpleXML (http://php.net/manual/en/book.simplexml.php) 读取 XML 输入,然后使用 json_encode (http://php.net/manual/en/book.json .php) 来创建输出。

      您可能只想遍历节点列表并将所有内容放入数组中,使用标签名称作为键,应该相当简单。

      【讨论】:

        【解决方案4】:

        这样的?

        <?php
        
        $xmlstr = "<item>
         <Barcode>0602527522593</Barcode>
         <albumid>1818</albumid>
         <Title>Gold</Title>
         <Country>Sweden</Country>
         <Format>CD</Format>
         <Length></Length>
         <Number_of_Discs></Number_of_Discs>
         <Type>album</Type>
         <Description></Description>
         <Band_or_Artist>Adams, Ryan</Band_or_Artist>
        </item>";
        
        $movies = new SimpleXMLElement($xmlstr);
        echo $output = json_encode($movies);
        ?>
        

        【讨论】:

          猜你喜欢
          • 2023-04-09
          • 1970-01-01
          • 1970-01-01
          • 2015-04-12
          • 1970-01-01
          • 2020-09-12
          • 1970-01-01
          • 1970-01-01
          • 2012-05-03
          相关资源
          最近更新 更多