PHP 将带有简单 XML 元素对象的数组转换为 XML
PHP convert Array with SimpleXMLElement Object to XML
我有一个包含一些简单XML元素对象的数组,现在我需要为 Ajax 交互获得一个格式正确的 XML,我该怎么做?
这是数组:
Array (
[0] => SimpleXMLElement Object (
[count] => 2
[id] => 20
[user_id] => 2
[title] => Polo RL )
[1] => SimpleXMLElement Object (
[count] => 3
[id] => 19
[user_id] => 4
[title] => tshirt fitch )
[2] => SimpleXMLElement Object (
[count] => 2
[id] => 18
[user_id] => 2
[title] => Polo La Martina )
)
我会得到这个 XML 结果:
<root>
<record>
<count>2</count>
<id>20</id>
<user_id>2</user_id>
<title>Polo RL</title>
</record>
<record>
<count>3</count>
<id>19</id>
<user_id>4</user_id>
<title>tshirt fitch</title>
</record>
<record>
<count>2</count>
<id>18</id>
<user_id>2</user_id>
<title>Polo La Martina</title>
</record>
</root>
我会使用 SimpleXMLElement 的 asXML 方法输出每个 object.So 的 XML this:
$xml = <<<XML
<record>
<count>2</count>
<id>20</id>
<user_id>2</user_id>
<title>Polo RL</title>
<record>
XML;
$xml = new SimpleXMLElement($xml);
echo $xml->asXML();
将输出:
<record>
<count>2</count>
<id>20</id>
<user_id>2</user_id>
<title>Polo RL</title>
<record>
因此,您可以简单地遍历数组,将每个元素 xml 输出到一个变量,如下所示:
$fullXml = '<root>';
foreach($arrXml as $xmlElement){
$fullXml .= str_replace('<?xml version="1.0"?>', '',$xmlElement->asXML());
}
$fullXml .= '</root>';
echo $fullXml ;
我有一个包含一些简单XML元素对象的数组,现在我需要为 Ajax 交互获得一个格式正确的 XML,我该怎么做?
这是数组:
Array (
[0] => SimpleXMLElement Object (
[count] => 2
[id] => 20
[user_id] => 2
[title] => Polo RL )
[1] => SimpleXMLElement Object (
[count] => 3
[id] => 19
[user_id] => 4
[title] => tshirt fitch )
[2] => SimpleXMLElement Object (
[count] => 2
[id] => 18
[user_id] => 2
[title] => Polo La Martina )
)
我会得到这个 XML 结果:
<root>
<record>
<count>2</count>
<id>20</id>
<user_id>2</user_id>
<title>Polo RL</title>
</record>
<record>
<count>3</count>
<id>19</id>
<user_id>4</user_id>
<title>tshirt fitch</title>
</record>
<record>
<count>2</count>
<id>18</id>
<user_id>2</user_id>
<title>Polo La Martina</title>
</record>
</root>
我会使用 SimpleXMLElement 的 asXML 方法输出每个 object.So 的 XML this:
$xml = <<<XML
<record>
<count>2</count>
<id>20</id>
<user_id>2</user_id>
<title>Polo RL</title>
<record>
XML;
$xml = new SimpleXMLElement($xml);
echo $xml->asXML();
将输出:
<record>
<count>2</count>
<id>20</id>
<user_id>2</user_id>
<title>Polo RL</title>
<record>
因此,您可以简单地遍历数组,将每个元素 xml 输出到一个变量,如下所示:
$fullXml = '<root>';
foreach($arrXml as $xmlElement){
$fullXml .= str_replace('<?xml version="1.0"?>', '',$xmlElement->asXML());
}
$fullXml .= '</root>';
echo $fullXml ;