首页 > 解决方案 > 如何将已由 SimpleXMLElement 和 xpath 转换的 xml 转换回 php 中的字符串?

问题描述

我使用 SimpleXMLElement 和 xpath 将此字符串转换为数组。

<?xml version="1.0" encoding="UTF-8"?>
 <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Body>
   <epos-print xmlns="http://www.epson-pos.com/schemas/2014/05/epos-print"><pulse/>
    <text align="center" ul="0" em="0" dw="1" dh="1" smooth="1" lang="de">Shoppingqueen</text>
    <feed/>
    <text align="center" ul="0" em="0" dw="0" dh="0" smooth="1" lang="de">Text me</text>
    <feed/>
    <text align="center" ul="0" em="0" dw="0" dh="0" smooth="1" lang="de">Hello People</text>
    <feed/>
    <text align="left" ul="0" em="0" dw="0" dh="0" smooth="0" lang="de">Hello world</text>
    <feed line="2"/>
    <text align="center" ul="0" em="0" dw="0" dh="0" smooth="0" lang="de">Some text</text>
    <feed line="2"/>
    <text align="left" ul="0" em="0" dw="0" dh="0" smooth="0" lang="de">Chocolate                         20,00 EUR A</text>
    <feed/>
    <text align="left" ul="1" em="0" dw="0" dh="0" smooth="0" lang="de">Apples                      15,00 EUR A</text>
    <feed/>
    <text align="left" ul="0" em="1" dw="0" dh="0" smooth="0" lang="de">Onion                   35,00 EUR  </text>
    <feed line="2"/>
    <text align="left" ul="0" em="0" dw="0" dh="0" smooth="0" lang="de">Cash                     35,00 EUR  </text>
    <cut/>
   </epos-print>
  </s:Body>
</s:Envelope>

这就是如何将其转换为对象数组的方式。

$xml = new SimpleXMLElement($xmlText);

$texts = $xml->xpath("epos-print/text");

转换后,我更改了节点内的一些值。例如,我将巧克力改为香草。现在我需要将它转换回相同的字符串(当然还有更改的节点值),以便将其保存在数据库中。我该怎么做?根据 php api,toString 不起作用并且 asXML() 不起作用,我收到错误消息 asXML 不能在数组上使用。

请帮忙。

标签: phpxmlxpath

解决方案


您需要调用asXML()原始对象:

$xml = new SimpleXMLElement($xmlText);

$texts = $xml->xpath("epos-print/text");

// Change chocolate to vanilla

$new_xml = $xml->asXML();

根据文档或xpath()方法:

如果发生错误,则返回 SimpleXMLElement 对象的数组或 FALSE。

所以 xpath 的返回是一个 simplexml 对象的数组,默认通过引用分配。


推荐阅读