我有一个xml文档,在节点名称中包含空格和等号。我正在尝试使用SimpleXML从这些节点中提取数据,但无论我尝试什么,它都会返回空白。
xml文档的示例
<code><away>
<radio>url.here</radio>
<live bitrate="1">url.here</live>
<live bitrate="0">url.here</live>
</away></code>
我尝试过同时使用echo "<td>".$node->away->{'live bitrate="1"'}."</td>";
echo "<td>".$node->away->{'live'}->{'bitrate="1"'}."</td>";
答案 0 :(得分:1)
这是我用来将SimpleXML对象转换为数组的函数:
public function simpleXMLToArray($xml,
$flattenValues=true,
$flattenAttributes = true,
$flattenChildren=true,
$valueKey='@value',
$attributesKey='@attributes',
$childrenKey='@children'){
$return = array();
if(!($xml instanceof SimpleXMLElement)){return $return;}
$name = $xml->getName();
$_value = trim((string)$xml);
if(strlen($_value)==0){$_value = null;};
if($_value!==null){
if(!$flattenValues){$return[$valueKey] = $_value;}
else{$return = $_value;}
}
$children = array();
$first = true;
foreach($xml->children() as $elementName => $child){
$value = $this->simpleXMLToArray($child, $flattenValues, $flattenAttributes, $flattenChildren, $valueKey, $attributesKey, $childrenKey);
if(isset($children[$elementName])){
if($first){
$temp = $children[$elementName];
unset($children[$elementName]);
$children[$elementName][] = $temp;
$first=false;
}
$children[$elementName][] = $value;
}
else{
$children[$elementName] = $value;
}
}
if(count($children)>0){
if(!$flattenChildren){$return[$childrenKey] = $children;}
else{$return = array_merge($return,$children);}
}
$attributes = array();
foreach($xml->attributes() as $name=>$value){
$attributes[$name] = trim($value);
}
if(count($attributes)>0){
if(!$flattenAttributes){$return[$attributesKey] = $attributes;}
else{$return = array_merge($return, $attributes);}
}
return $return;
}