【问题标题】:How print array to Xml with PHP如何使用 PHP 将数组打印到 XML
【发布时间】:2021-03-28 06:43:35
【问题描述】:

看到他用数字和一个代替“codDedido”。我需要它是 xml 格式.. 但我不知道我哪里出错了。 我像这样填充它:

$listaDados[pedido][listItem][0][codItem]=123;
$listaDados[pedido][listItem][1][codItem]=456;

这是我的功能,:

function array_to_xml2($array, &$xml_user_info) {
    foreach($array as $key => $value) {
        if(is_array($value)) {
            if(!is_numeric($key)){
                $subnode = $xml_user_info->addChild("$key");
                self::array_to_xml2($value, $subnode); 
            }else{
                $subnode = $xml_user_info->addChild("$key");
                self::array_to_xml2($value, $subnode); 
            }
        }else{
            $xml_user_info->addChild("$key",htmlspecialchars("$value"));
        }
    }

这里是我的称呼:

foreach ($listaDados['pedido']['listaPedItem'] as $listaD) {
    $teste['listaPedItem'] = $listaD; 
    self::array_to_xml2($teste,$xml_user_info);
    var_dump($listaD);
}

所以我需要它:

<pedido>
    <listPedItem>
        <codPedido>123</codPedido>
    </listPedItem>
    <listPedItem>
        <codPedido>456</codPedido>
    </listPedItem>
</pedido>

但我不知道它会返回:

<pedido>
   <listPedItem>
    <0>
        <codPedido>
    </0>
    <1>
        <codPedido>
    </1>
  </listPedItem>
</pedido>

【问题讨论】:

  • 什么是$xml_user_info?为什么将对象作为参考传递?你能做一个独立的例子吗(没有$thisself等)
  • 你好@AterLux,tnks 回答.. 所以在我做:$xml_user_info = new SimpleXMLElement("&lt;?xml version=\"1.0\"?&gt;&lt;pedido&gt;&lt;/pedido&gt;");self::array_to_xml2($listaDados,$xml_user_info);

标签: php arrays xml


【解决方案1】:

也许可以从官方 PHP 页面试试这个功能

<?php 
function array2XML($arr,$root) { 
$xml = new SimpleXMLElement("<?xml version=\"1.0\" encoding=\"utf-8\" ?><{$root}></{$root}>"); 
$f = create_function('$f,$c,$a',' 
        foreach($a as $v) { 
            if(isset($v["@text"])) { 
                $ch = $c->addChild($v["@tag"],$v["@text"]); 
            } else { 
                $ch = $c->addChild($v["@tag"]); 
                if(isset($v["@items"])) { 
                    $f($f,$ch,$v["@items"]); 
                } 
            } 
            if(isset($v["@attr"])) { 
                foreach($v["@attr"] as $attr => $val) { 
                    $ch->addAttribute($attr,$val); 
                } 
            } 
        }'); 
$f($f,$xml,$arr); 
return $xml->asXML(); 
} 
?>

Source

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-08
    • 1970-01-01
    • 2011-11-08
    • 1970-01-01
    • 2013-02-28
    • 2018-10-23
    相关资源
    最近更新 更多