簡體   English   中英

PHP Array to XML,但格式不同

[英]PHP Array to XML, but format differently

我有一個可以成功創建xml文件的PHP數組。但是,我需要更改XML文件中的格式。 當前,它產生以下內容:

<markers>
    <marker>
        <info1></info1>
        <info2></info2>
    </marker>
</markers>

我需要像這樣顯示:

<markers>
    <marker info1="43.5" info2="-79.6888888888889" />
</markers>

這是我用來從PHP數組創建XML文件的PHP代碼

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

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

//saving generated xml file
$xml_student_info->asXML('xmltest.xml');


// function defination to convert array to xml
function array_to_xml($store, &$xml_student_info) {
    foreach($store 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("marker");
                array_to_xml($value, $subnode);
            }
        }
        else {
            $xml_student_info->addChild("$key","$value");
        }
    }
}

謝謝你的幫助!

您需要使用方法addAttribute。 看看下面我的代碼:)

<?php
$xml_student_info = new SimpleXMLElement("<?xml version=\"1.0\"?><markers></markers>");

$store = array(
                array('attr1' => 'test', 'attr2' => 'test'),
                array('attr3' => 'test', 'attr4' => 'test'),
            );
array_to_xml($store, $xml_student_info);

$xml_student_info->asXML('xmltest.xml');

function array_to_xml($store, &$xml_student_info) {
    foreach($store as $key => $value) {
        if (is_array($value)) {
            $child = $xml_student_info->addChild("marker");
            foreach($value as $k => $v) {
                $child->addAttribute("$k","$v");
            }
        } else {
            $child = $xml_student_info->addChild("marker");
            $child->addAttribute("$key","$value");
        }
    }
}

?>

輸出量

<?xml version="1.0"?>
<markers><marker attr1="test" attr2="test"/><marker attr3="test" attr4="test"/></markers>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM