如何详细说明反映以下xml结构的数组?
提前谢谢。
XML源:
<document>
<section type="group" width="100">
<section type="list" width"50"/>
<style>classe1 {color:red}</style>
<section type="text" height="25">azerty</section>
</section>
</document>请注意嵌入在第一级“部分”中的三个标签(“节”、“样式”然后“节”)。
所需生成数组的示例应该反映这种嵌入、属性和标记顺序:
Array
{
[0]=>Array
{
[key]=>section
[attributes]=>Array
{
[type]=>group
[width]=>100
}
[0]=>Array
{
[key]=>section
[attributes]=>Array
{
[type]=>list
[width]=>50
}
}
[1]=>Array
{
[key]=>style
[content]=>classe1 {color:red}
}
[2]=>Array
{
[key]=>section
[attributes]=>Array
{
[type]=>text
[width]=>25
}
[content]=>azerty
}
}
}我尝试了这段代码,但没有成功:
<?php
function xml2array($fName)
{
$sxi = new SimpleXmlIterator($fName, null, true);
return sxiToArray($sxi);
}
function sxiToArray($sxi)
{
$a = array();
for( $sxi->rewind(); $sxi->valid(); $sxi->next() )
{
if(!array_key_exists($sxi->key(), $a))
$a[$sxi->key()] = array();
if($sxi->hasChildren())
$a[$sxi->key()][] = sxiToArray($sxi->current());
else
{
$a[$sxi->key() ]['attributs'] = $sxi->attributes();
$a[$sxi->key()][] = strval($sxi->current());
}
}
return $a;
}
try
{
$catArray = xml2array("temp.xml");
echo '<pre>'.print_r($catArray,true);
}
catch(Exception $e)
{
echo 'ERREUR : '.$e->getMessage();
}
?>发布于 2017-10-02 13:25:58
我已经更新了代码以实现我认为你之后的目标。在有些地方,我对数组进行了不同的管理。特别是使用属性--我一次只添加一个属性,以便创建键/值设置。
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
function xml2array($fName)
{
$sxi = new SimpleXmlIterator($fName, null, true);
$sxi->rewind();
return sxiToArray($sxi)[0];
}
function sxiToArray($sxi)
{
$a = array();
for( $sxi->rewind(); $sxi->valid(); $sxi->next() )
{
$newData = [];
$newData['key'] = $sxi->key();
foreach ( $sxi->current()->attributes() as $key=>$attribute) {
$newData['attributes'][(string)$key] = (string)$attribute;
}
if($sxi->hasChildren()) {
$newData = array_merge( $newData, sxiToArray($sxi->current()));
}
else
{
if ( strlen(strval($sxi->current())) > 0 ) {
$newData['content'] = strval($sxi->current());
}
}
$a[] = $newData;
}
return $a;
}
try
{
$catArray = xml2array("t1.xml");
echo '<pre>'.print_r($catArray,true);
}
catch(Exception $e)
{
echo 'ERREUR : '.$e->getMessage();
}
{
echo 'ERREUR : '.$e->getMessage();
}我还必须将XML更正为
<section type="list" width"50"/>应该是
<section type="list" width="50"/>(缺少=)
https://stackoverflow.com/questions/46525149
复制相似问题