php - 如何将已由 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 不能在数组上使用。
请帮忙。
解决方案
您需要调用asXML()
原始对象:
$xml = new SimpleXMLElement($xmlText);
$texts = $xml->xpath("epos-print/text");
// Change chocolate to vanilla
$new_xml = $xml->asXML();
根据文档或xpath()
方法:
如果发生错误,则返回 SimpleXMLElement 对象的数组或 FALSE。
所以 xpath 的返回是一个 simplexml 对象的数组,默认通过引用分配。
推荐阅读
- vb.net - 在驱动器中搜索包含确切单词的文本文件并进行更改
- python - Django Rest Framework 我不能使用有外键的序列化程序保存模型
- bash - Linux bash脚本:将ls与glob一起使用并在变量中获取输出不起作用
- reactjs - 反应选择组合框可访问性。屏幕阅读器未宣布提供的选项
- django - 合并模型并发送到模板
- android - 在没有应用程序上下文或电话权限的情况下生成唯一的设备 ID
- apache-spark - 时间戳转换使值 null
- java - 如何从java jar访问外部文件
- python - 从应用程序机器人向松弛用户发送直接消息,但不在应用程序频道中
- html - 从 HTML 页面检索标签以将它们导入另一个 HTML 文件