1

我正在尝试构建一个 3d php 数组,最终以 xml 格式输出……这是我试图用来证明这个概念的代码……

$test = array('apple','orange');
$results = Array(
  'success' => '1',
  'error_number' => '',
  'error_message' => '',
  'results' => Array (
       'number_of_reports' => mysql_num_rows($run),
       'item' => $test
   )
);

我希望得到的数组看起来像

<success>1</success>
<error_number/>
<error_message/>
<results>
     <number_of_reports>18</number_of_reports>
     <item>
         <0>apple</0>
         <1>orange</1>
     </item>
</results>

实际上,苹果和橙色阵列本身就是一个 3d 阵列......如果你曾经使用过 ebay api......你就会知道我想要做什么(我认为)

4

2 回答 2

2

试试看:

代码:

<?php
$test = array('apple','orange');
$results = Array(
  'success' => '1',
  'error_number' => '',
  'error_message' => '',
  'results' => Array (
       'number_of_reports' => 1,
       'item' => $test
   )
);

print_r($results);
function addChild1($xml, $item, $clave)
{
    if(is_array($item)){
        $tempNode = $xml->addChild($clave,'');
        foreach ($item as $a => $b)
        {
            addChild1($tempNode, $b, $a);
        }           
    } else {
        $xml->addChild("$clave", "$item");
    }
}

$xml = new SimpleXMLElement('<root/>');
addChild1($xml, $results,'data');
$ret = $xml->asXML();

print $ret;

输出:

<?xml version="1.0"?>
<root><data><success>1</success><error_number></error_number><error_message></error_message><results><number_of_reports>1</number_of_reports><item><0>apple</0><1>orange</1></item></results></data></root>
于 2012-09-07T03:41:38.860 回答
0

请参阅下面的网址。我认为它对你很有用:-

如何将数组转换为 SimpleXML

或试试看:-

$xml = new SimpleXMLElement('<root/>');
array_walk_recursive($test_array, array ($xml, 'addChild'));
print $xml->asXML();
于 2012-09-06T12:52:58.157 回答