Yas*_*984 1 php xml parsing simplexml
我试图找到一种方法将任何xml feed转换为关联数组,我注意到很多其他人都在寻找相同的东西,并且有很多尝试,其中一些已经失败,我发现了以下方法,信用去
http://gaarf.info/2009/08/13/xml-string-to-php-array/
我略微改变了代码,这是结果.
function xmlNameSpaceToArray(SimpleXmlIterator $xml, $nameSpaces=Null){
$output = Null;
$preparedArray = array();
for($xml->rewind(); $xml->valid(); $xml->next()) {
$key = $xml->key();
if(!isset($preparedArray[$key])) { $preparedArray[$key] = array(); $i=0; }
else $i = count($preparedArray[$key]);
$simple = true;
foreach($xml->current()->attributes() as $k=>$v) {
$preparedArray[$key][$i][$k]=(string)$v;
$simple = false;
}
if($nameSpaces) foreach($nameSpaces as $nid=>$name) {
foreach($xml->current()->attributes($name) as $k=>$v) {
$preparedArray[$key][$i][$nid.':'.$k]=(string)$v;
$simple = false;
}
}
if($xml->hasChildren()) {
if($simple) $preparedArray[$key][$i] = xmlNameSpaceToArray($xml->current(), $nameSpaces);
else $preparedArray[$key][$i]['content'] = xmlNameSpaceToArray($xml->current(), $nameSpaces);
} else {
if($simple) $preparedArray[$key][$i] = strval($xml->current());
else $preparedArray[$key][$i]['content'] = strval($xml->current());
}
$i++;
}
$output = $preparedArray;
return $preparedArray;
}
function xmlToArray($xmlFilePath){
$xml = new SimpleXmlIterator($xmlFilePath , null, true);
$nameSpaces = $xml->getNamespaces(true);
$output = xmlNameSpaceToArray($xml,$nameSpaces);
return $output;
}
$xmlFilePath = 'http://forums.devshed.com/rss/feed-5.xml';
$output = xmlToArray($xmlFilePath);
print_r($output);
Run Code Online (Sandbox Code Playgroud)
我想要现在找出是,这可能有潜在的问题,我们的目标是,使这项工作对于每一个结构良好的XML饲料,没有任何PHP警告,通知也不会丢失任何数据.
你能找到这个或一个不起作用的饲料的缺陷吗?它适用于我测试过的所有内容.
最简单的方法是使用内置函数,然后转换为数组.
<?php
$obj = simplexml_load_string($xml); // Parse XML
$array = json_decode(json_encode($obj), true); // Convert to array
?>
Run Code Online (Sandbox Code Playgroud)