2012-07-11 99 views
19

有沒有更優雅的方法來將SimpleXML屬性轉義爲數組?SimpleXML屬性到數組

$result = $xml->xpath($xpath); 
$element = $result[ 0 ]; 
$attributes = (array) $element->attributes(); 
$attributes = $attributes[ '@attributes' ]; 

我真的不想循環它只是爲了提取鍵/值對。我需要的只是把它放到一個數組中,然後傳遞給它。我會認爲attributes()會默認完成它,或者至少給出選項。但我甚至無法在任何地方找到上述解決方案,所以我不得不自己弄清楚。我是否過分複雜化了這個或者什麼?

編輯:

現在我還用上面的腳本,直到我肯定知道是否訪問@屬性數組是安全與否

回答

11

不要直接閱讀'@attributes'屬性,這是內部使用。無論如何,attributes()已經可以作爲一個數組使用,而不需要「轉換」爲真正的數組。

例如:

<?php 
$xml = '<xml><test><a a="b" r="x" q="v" /></test><b/></xml>'; 
$x = new SimpleXMLElement($xml); 

$attr = $x->test[0]->a[0]->attributes(); 
echo $attr['a']; // "b" 

如果你希望它是一個「真正的」數組,你得循環:

$attrArray = array(); 
$attr = $x->test[0]->a[0]->attributes(); 

foreach($attr as $key=>$val){ 
    $attrArray[(string)$key] = (string)$val; 
} 
+0

是的,但問題在於它仍然認爲自己是SimpleXML元素,因此您必須將'$ attr ['a']'轉換爲字符串才能正常工作。我將這個數組傳遞給另一個不知道它應該是什麼類型的類,只是它需要是一個數組。 – mseancole 2012-07-11 19:39:15

+0

啊,你在編輯中得到它...循環比我目前做的更好嗎?我會認爲這樣做沒有循環會更快。 – mseancole 2012-07-11 19:42:40

+0

@showerhead:我不知道這是否更好,但我總是學會不要直接閱讀「@屬性」屬性。 – 2012-07-11 19:53:22

0

我想你會通過有循環。一旦你讀到XML,你可以把它放入數組中。

<?php 
function objectsIntoArray($arrObjData, $arrSkipIndices = array()) 
{ 
$arrData = array(); 

// if input is object, convert into array 
if (is_object($arrObjData)) { 
    $arrObjData = get_object_vars($arrObjData); 
} 

if (is_array($arrObjData)) { 
    foreach ($arrObjData as $index => $value) { 
     if (is_object($value) || is_array($value)) { 
      $value = objectsIntoArray($value, $arrSkipIndices); // recursive call 
     } 
     if (in_array($index, $arrSkipIndices)) { 
      continue; 
     } 
     $arrData[$index] = $value; 
    } 
} 
return $arrData; 
} 

$xmlStr = file_get_contents($xml_file); 
$xmlObj = simplexml_load_string($xmlStr); 
$arrXml = objectsIntoArray($xmlObj); 

foreach($arrXml as $attr) 
    foreach($attr as $key->$val){ 
if($key == '@attributes') .... 
} 
+1

什麼是'objectsIntoArray'?另外,你不應該直接讀'@ attributes',這就是' - > attributes()'的用處。 – 2012-07-11 19:49:40

+0

對不起,我從我的代碼中刪除了剛剛編輯它的頂部部分。 – PoX 2012-07-11 20:24:47

40

更優雅的方式;它可以讓你在不使用$屬性[ '@屬性']相同的結果:

$attributes = current($element->attributes()); 
+0

絕對簡單,緊湊,操作少。 – 2013-10-17 00:59:53

+0

@silverskater:非常有用,它適合我!非常感謝 – 2013-12-23 07:06:28

+0

這應該是答案 – kfriend 2014-12-15 15:42:29