2011-03-11 68 views
1

我有一个xml文档,其中包含节点名称中的空格和等号。我试图使用SimpleXML从这些节点中提取数据,但无论我尝试什么,它都会返回空白。节点名称中带有空格和等号的SimpleXML节点

我已经使用这两种echo "<td>".$node->away->{'live bitrate="1"'}."</td>"; echo "<td>".$node->away->{'live'}->{'bitrate="1"'}."</td>";

+0

嗯。 ..我不知道如何告诉你,但这些不是“节点名称中的空格和等号”;这些是*属性*。 http://w3schools.com/xml/default.asp – 2011-03-11 01:02:30

回答

1

这里试图xml文档

<code><away> 
    <radio>url.here</radio> 
    <live bitrate="1">url.here</live> 
    <live bitrate="0">url.here</live> 
    </away></code> 

的样品是我使用的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; 
    }