2011-03-11 72 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; 
    }