如何在 PHP 条件下将数组转换为 XML

How To Convert Array To XML With Condition On PHP

我有PHP这样的代码:

public function get_xml_product($serviceName) {
        $product    = Array();
        $idx        = $idx2 = 0;
        $explodeResult=explode(", ",$serviceName);
        foreach($explodeResult as $value)
        {
              $sql = "SELECT id,parent,code,name,xs1 as DOWNLOAD, xs2 as UPLOAD
                       FROM sc_params
                      WHERE rfen = 'SERVICE_REQUESTED'
                      AND code = '".$value."' 
                        OR code IN
                        ( 
                            SELECT code 
                             FROM sc_params 
                             WHERE rfen = 'SERVICE_REQUESTED'
                             AND id = (
                            SELECT parent 
                                 FROM sc_params 
                                 WHERE rfen = 'SERVICE_REQUESTED' 
                                 AND code = '".$value."' )
                        )
                    ";          
            $stmt = oci_parse($this->_conn,$sql);
            $rs = oci_execute($stmt);
            if (!$rs) {
                $error = oci_error();
                $this->_err = $error;
                return false;
            }

            while ($data = oci_fetch_array($stmt, OCI_BOTH)) {
                if($data['PARENT'] == 0) {
                    $idx++;
                    $product[$idx]['id']        = $data['ID'];
                    $product[$idx]['name']      = $data['NAME'];
                }
                else {
                    foreach($product as $product2)
                    {
                    $product[$idx]['download'][$idx2]['name']   = 'DOWNLOAD';
                    $product[$idx]['download'][$idx2]['value'] = $data['DOWNLOAD'];
                    $product[$idx]['upload'][$idx2]['name']   = 'UPLOAD';
                    $product[$idx]['upload'][$idx2]['value'] = $data['UPLOAD'];
                    $idx2++;
                    }
                } 
            }
        }
        print_r($product);
......

结果显示:

 Array
    (
        [1] => Array
            (
                [id] => 1
                [name] => INTERNET
                [download] => Array
                    (
                        [0] => Array
                            (
                                [name] => DOWNLOAD
                                [value] => 1024
                            )

                    )

                [upload] => Array
                    (
                        [0] => Array
                            (
                                [name] => UPLOAD
                                [value] => 256
                            )

                    )

            )

我想把它变成 xml 像这样:

<xml version="1.0"?>
         <services>
             <service>
                 <id>1</id>
                 <name>INTERNET</name>
                 <attribute>
                     <name>DOWNLOAD</name>
                     <value>1024</value>
                 </attribute>
                 <attribute>
                     <name>UPLOAD</name>
                     <value>512</value>
                 </attribute>
             </service>
</services>

更新: 我的 php 文件有 xml 格式的条件...我试过:

$xml = new SimpleXMLElement("<services/>");
        foreach($product as $key => $value) {
            if (is_array($value)) {
                $subnode = $xml->addChild("service");
                $this->array_to_xml($value, $subnode);
            } 
            else
            {
               $xml->addChild(htmlspecialchars("$key"),htmlspecialchars("$value"));
            }
        } 
        $string = $xml->asXML(); 
        $result = htmlentities($string);

它调用array_to_xml,这里是:

public function array_to_xml($product, &$xml) {
        foreach($product as $key => $value) {
            if (is_array($value)) {
                $subnode = $xml->addChild("service");
                array_to_xml($value, $subnode);
            } else {
               $xml->addChild(htmlspecialchars("$key"),htmlspecialchars("$value"));
            }
        }
        return $xml;
    }

它给出错误 500 Internal Server Error,但如果我删除 php 中的条件,它会 运行。

请帮帮我....

这里有大量 PHP 库,google 可能是一个不错的起点!: Php array to xml

您可以使用 SimpleXML: 此处解释:How to convert array to SimpleXML

文档:http://php.net/manual/en/book.simplexml.php

基本转换方式:

    <?php

$test_array = 数组 ( 'tmp1' => 'tmp2', 'tmp3' => 'tmp4', 'more_array' => 数组 ( 'tmps' => 'tmpx', ),); $xml = new SimpleXMLElement('');array_walk_recursive($test_array, array ($xml, 'addChild'));打印 $xml->asXML();

结果:

tmp1tmp3tmpx>tmps/root>

键和值被交换 - 可以在 array_walk.

之前用 array_flip() 修复

A_W_recursive 需要 PHP5,您可以使用 a_w,但 'tmps' => 'tmpx' 不起作用。

另一种方式(可重复,for-based)可以在这里看到: https://www.kerstner.at/en/2011/12/php-array-to-xml-conversion/

抱歉打码,本站的打码功能无法打码XML。 见图片: https://imgur.com/X45Q88j

这里是 PHP 5.2 代码,它将任意深度的数组转换为 xml 文档:

    Array
    (
    ['total_stud']=> 500
    [0] => Array
        (
            [student] => Array
                (
                    [id] => 1
                    [name] => abc
                    [address] => Array
                        (
                            [city]=>Lahore
                            [zip]=>54000
                        )                       
                )
        )
    [1] => Array
        (
            [student] => Array
                (
                    [id] => 2
                    [name] => xyz
                    [address] => Array
                        (
                            [city]=>Karachi
                            [zip]=>56000
                        )   
            )

        )
)

生成的 XML 将是:

<?xml version="1.0"?>
<student_info>
    <total_stud>500</total_stud>
    <student>
        <id>1</id>
        <name>abc</name>
        <address>
            <city>Lahore</city>
            <zip>54000</zip>
        </address>
    </student>
    <student>
        <id>1</id>
        <name>abc</name>
        <address>
            <city>Karachi</city>
            <zip>56000</zip>
        </address>
    </student>
</student_info>

这是代码片段

// creating object of SimpleXMLElement
$xml_student_info = new SimpleXMLElement("<?xml version=\"1.0\"?><student_info></student_info>");

// function call to convert array to xml
array_to_xml($student_info,$xml_student_info);

//saving generated xml file
$xml_student_info->asXML('file path and name');


// function defination to convert array to xml
function array_to_xml($student_info, &$xml_student_info) {
    foreach($student_info as $key => $value) {
        if(is_array($value)) {
            if(!is_numeric($key)){
                $subnode = $xml_student_info->addChild("$key");
                array_to_xml($value, $subnode);
            }
            else{
                $subnode = $xml_student_info->addChild("item$key");
                array_to_xml($value, $subnode);
            }
        }
        else {
            $xml_student_info->addChild("$key",htmlspecialchars("$value"));
        }
    }
}

?>

您可以使用 SimpleXML:通过 comments 中的适当讨论从 here 获得更多帮助。 对于您的自定义方式,请尝试 this.it 应该可以解决您的问题:

<?php

$test_array=Array
    (
        '1' => Array
            (
                'id' => 1,
                'name' => 'INTERNET',
                'download' => Array
                    (
                        '0' => Array
                            (
                                'name' => 'DOWNLOAD',
                                'value' => 1024
                            )

                    ),

                'upload' => Array
                    (
                        '0' => Array
                            (
                                'name' => 'UPLOAD',
                                'value' => 256
                            )

                    )

            )
            );
// creating object of SimpleXMLElement
$xml = new SimpleXMLElement("<?xml version=\"1.0\"?><services></services>");
$subnode=$xml->addChild("service");
array_to_xml($test_array[1],$subnode);

//saving generated xml file
print $xml->asXML('info.xml');// create an info.xml file is written successfully will print 1.

function array_to_xml($test_array, &$xml) {
    foreach($test_array as $key => $value) {
        if(is_array($value)) {
            if(!is_numeric($key)){
                $subnode = $xml->addChild("$key");
                array_to_xml($value, $subnode);
            }
            else{
                $subnode = $xml->addChild("attribute");
                array_to_xml($value, $subnode);
            }
        }
        else {
            $xml->addChild("$key",htmlspecialchars("$value"));
        }
    }
}

?>