问题描述
我有一个PHP脚本,该脚本从远程服务器提取XML文件,并使用simplexml_load_string和json_encode将其转换为JSON.但是,simplexml_load_string似乎忽略了内联属性,如下所示:
I have a PHP script that pulls an XML file from a remote server, and converts it to JSON using simplexml_load_string and json_encode. However, the simplexml_load_string seems to ignore inline attributes, like so:
<AxisFeedrate dataItemId="iid7" timestamp="2012-03-21T15:15:41-04:00" sequence="7" name="Yfrt" subType="ACTUAL" units="MILLIMETER/SECOND">UNAVAILABLE</AxisFeedrate>
在这种情况下,JSON表示形式为{AxisFeedrate:'UNAVAILABLE'}
In this case the JSON representation would be {AxisFeedrate: 'UNAVAILABLE'}
但是,我需要使那些属性可用.我一直在想的一个想法是替换字符串,将属性变成文本节点,如下所示:
However, I need to have those attributes available. One idea I've been approaching is replacing strings to turn the attributes into text nodes like so:
<AxisFeedrate>
<dataItemId>iid7</dataItemId>
<timestamp>2012-03-21T15:15:41-04:00</timestamp>
<sequence>7</sequence>
<name>Yfrt</name>
<subType>ACTUAL</subType>
<units>MILLIMETER/SECOND"</units>
<value>UNAVAILABLE</value>
</AxisFeedrate>
我可以使用常规查找/替换将属性转换为自己的标签元素,但是我无法将原始文本值包装在Value标记中,至少使用查找/替换是困难的.
I can turn the attributes into their own tag elements with regular find/replace, but I'm having trouble wrapping the original text value in a Value tag, at least with find/replace.
有什么好的方法可以做到这一点?上面的XML块位于不同数据项上的许多类似块的中间,因此我不能仅以> ...
What are some good approaches for doing this? The above chunk of XML is in the middle of many similar chunks on different data items, so I couldn't just start by replacing the first closing > with >...
推荐答案
您可以使用SimpleXML本身来读取属性.
You could use SimpleXML itself to read the attributes.
示例:
<?php
$xml=simplexml_load_string('<AxisFeedrate dataItemId="iid7" timestamp="2012-03-21T15:15:41-04:00" sequence="7" name="Yfrt" subType="ACTUAL" units="MILLIMETER/SECOND">UNAVAILABLE</AxisFeedrate>');
foreach($xml->attributes() as $k=>$v) {
echo $k." -> ".(string)$v."\n";
}
?>
输出:
dataItemId -> iid7
timestamp -> 2012-03-21T15:15:41-04:00
sequence -> 7
name -> Yfrt
subType -> ACTUAL
units -> MILLIMETER/SECOND
这篇关于如何将XML属性转换为文本节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!