PHP实现数组array转换成xml的方法

PHP可以通过SimpleXMLElement类来实现将数组转换为XML的操作,步骤如下:

PHP可以通过SimpleXMLElement类来实现将数组转换为XML的操作,步骤如下:

  1. 创建一个SimpleXMLElement对象。
$xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><root></root>');
  1. 将数组转换为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对象中。

  1. 输出生成的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的方法

基础教程推荐