PHP可以通过SimpleXMLElement类来实现将数组转换为XML的操作,步骤如下:
PHP可以通过SimpleXMLElement类来实现将数组转换为XML的操作,步骤如下:
- 创建一个SimpleXMLElement对象。
$xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><root></root>');
- 将数组转换为XML节点并添加到SimpleXMLElement对象中。
function arrayToXml($arr, &$xml) {
foreach ($arr as $key => $value) {
if (is_array($value)) {
$child = $xml->addChild($key);
arrayToXml($value, $child);
} else {
$xml->addChild($key, $value);
}
}
}
上述代码中的arrayToXml函数将传入的数组转换为XML节点并递归地添加到SimpleXMLElement对象中。
- 输出生成的XML字符串。
header("Content-type: text/xml");
echo $xml->asXML();
完整示例:
$arr = array(
"name" => "John Doe",
"age" => 30,
"address" => array(
"street" => "123 Main St",
"city" => "Anytown",
"state" => "CA",
"zip" => "12345"
)
);
$xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><root></root>');
arrayToXml($arr, $xml);
header("Content-type: text/xml");
echo $xml->asXML();
输出结果:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<name>John Doe</name>
<age>30</age>
<address>
<street>123 Main St</street>
<city>Anytown</city>
<state>CA</state>
<zip>12345</zip>
</address>
</root>
另一个示例:
$arr = array(
"book" => array(
array(
"title" => "Harry Potter and the Philosopher's Stone",
"author" => "J.K. Rowling",
"year" => 1997
),
array(
"title" => "The Hitchhiker's Guide to the Galaxy",
"author" => "Douglas Adams",
"year" => 1979
)
)
);
$xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><root></root>');
arrayToXml($arr, $xml);
header("Content-type: text/xml");
echo $xml->asXML();
输出结果:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<book>
<item>
<title>Harry Potter and the Philosopher's Stone</title>
<author>J.K. Rowling</author>
<year>1997</year>
</item>
<item>
<title>The Hitchhiker's Guide to the Galaxy</title>
<author>Douglas Adams</author>
<year>1979</year>
</item>
</book>
</root>
沃梦达教程
本文标题为:PHP实现数组array转换成xml的方法


猜你喜欢
- laravel 错误处理,接口错误返回json代码 2023-03-12
- PHP7中I/O模型内核剖析详解 2023-01-07
- PHP实现的数据对象映射模式详解 2023-01-04
- tp5 + ajax 引入阿里云短信发送验证码 2023-08-30
- 使用Laravel中的查询构造器实现增删改查功能 2023-02-06
- PHP设计模式之模板模式定义与用法详解 2022-12-01
- Laravel中Kafka的使用详解 2023-06-03
- PHP实现随机发扑克牌 2023-04-08
- PHP实现数组向任意位置插入,删除,替换数据操作示例 2023-01-05
- PHP可变函数学习小结 2023-12-12