将数据库中的多维数组解析为XML文件(解析错误)

时间:2016-09-12 10:51:52

标签: php arrays xml

我想将多维数组解析为xml文件。但是我的xml文件显示了一个包含所有项目的长字符串,而不是正确的布局。

我的代码:

这个数组只是我想要放入xml文件的3000多个数组中的一个。

Array
(
    [0] => Array
        (
            [line_item_id] => 23
            [order_id] => 9
            [type] => product
            [line_item_label] => 10101001
            [quantity] => 1.00
            [created] => 1361126884
            [changed] => 1361126884
            [data] => Array
                (
                    [context] => Array
                        (
                            [product_ids] => Array
                                (
                                    [0] => 6
                                )

                            [add_to_cart_combine] => 1
                            [show_single_product_attributes] => 0
                            [display_path] => node/15
                            [entity] => Array
                                (
                                    [entity_type] => node
                                    [entity_id] => 15
                                    [product_reference_field_name] => field_products
                                )

                        )

                )

        )

功能:

function array_to_xml($array, $xml_options) {
        foreach($array as $key => $value) {
            if(is_array($value)) {
                if(!is_numeric($key)){
                    $subnode = $xml_options->addChild("$key");
                    array_to_xml($value, $subnode);
                }else{
                    $subnode = $xml_options->addChild("item$key");
                    array_to_xml($value, $subnode);
                }
            }else {
                $xml_options->addChild("$key",htmlspecialchars("$value"));
            }
        }
    }

将其放入xml文件的代码:

$xml = new SimpleXMLElement("<?xml version=\"1.0\"?><Products></Products>");
$data = get_data();
array_to_xml($data,$xml);
$xml_file = $xml->asXML('products.xml'); 

这只是在我的xml文件中输出一个长字符串。我做错了什么?

更新

我发现数据库中的某些数据使用0作为键。但是我的代码似乎没有把它改成别的东西。我会调查一下。

0 个答案:

没有答案