如何将已由SimpleXMLElement和xpath转换的xml转换回php中的String?

时间:2018-08-22 14:47:38

标签: php xml xpath

我将此字符串转换为具有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不能在数组上使用。

请帮助。

1 个答案:

答案 0 :(得分:1)

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

$xml = new SimpleXMLElement($xmlText);

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

// Change chocolate to vanilla

$new_xml = $xml->asXML();

根据文档或xpath()方法:

  

在出现错误的情况下返回SimpleXMLElement对象的数组或FALSE。

因此,xpath的返回是一个由simplexml对象组成的数组,这些对象默认情况下是通过引用分配的。