2013-04-04 12 views
13

我有這樣的代碼:現在如何的DOMNodeList對象轉換成數組

 $dom = new DOMDocument(); 
    $dom->load('file.xml'); 
    $names = $dom->getElementsByTagName('name'); 

$names是的DOMNodeList對象,我需要把這個對象轉換成一個數組,

 $names = (array)$names; 
    var_dump($names); // empty array 

上面的代碼呢不工作並返回一個空數組,爲什麼?

回答

7

爲什麼(array)不工作?因爲DOMNodeList對象只有一個屬性,length,它是整數類型:

If an object is converted to an array, the result is an array whose elements are the object's properties. The keys are the member variable names, with a few notable exceptions: integer properties are unaccessible; private variables have the class name prepended to the variable name; protected variables have a '*' prepended to the variable name. These prepended values have null bytes on either side.

由於DOMNodeList實現Traversable接口,這是相當容易地創建自己的數組:

$array = array(); 
foreach($names as $node){ 
    $array[] = $node; 
} 

編輯:我刪除了最初的解釋,因爲它不適用於此。什麼是人工的手段是用數字名稱屬性傳遞到數組,但不能讀:

<?php 

class Foo{ 
    public function __construct(){ 
     $this->{123} = 456; 
    } 
} 

$array = (array)new Foo; 
var_dump($array); 
var_dump($array['123']); 
array(1) { 
    ["123"]=> 
    int(456) 
} 

Notice: Undefined offset: 123 in D:\tmp\borrame.php on line 11 
NULL 

的解釋可能更上線即DOMNodeList不與PHP代碼創建了一個用戶對象,但C中定義的內置對象,因此適用不同的規則。

3

只是想迭代槽的元素,並把它們放到一個數組:

$names_array = array(); 
foreach ($names as $name) { 
    $names_array[] = $name; // this is a DOMNode instance 
    // you might want to have the textContent of them like this 
    $names_array[] = $name->textContent; 
} 

這樣,他們仍然會DOMNode實例一樣,你可能希望得到他們的textContent財產。

0
$dom = new DOMDocument(); 
$dom->load('file.xml'); 
$names = $dom->getElementsByTagName('name'); 
$headlines = array(); 

foreach($names as $name) { 
    $headline = array(); 
    if($name->childNodes->length) { 
     foreach($name->childNodes as $i) { 
      $headline[$i->nodeName] = $i->nodeValue; 
     } 
    } 

    $headlines[] = $headline; 
} 
39

使用iterator_to_array()到的DOMNodeList轉換爲數組

$document = new DomDocument(); 
$document->load('test.xrds'); 
$nodeList = $document->getElementsByTagName('Type'); 
$array = iterator_to_array($nodeList); 
+1

這應該是正確的答案。它的工作原理非常簡單。 – 2014-08-27 12:32:25

+0

同意。這是最好的。 – 2015-04-10 19:36:45

+1

這不適合我。 '可捕獲的致命錯誤:傳遞給iterator_to_array()的參數1必須實現接口Traversable,DOMNodeList的實例給定' – 2015-05-26 20:34:27

0

假設你想要的實際值,而不是創建DOM數組節點:

foreach($nodelist as $node) { 
    $values[] = $node->nodeValue; 
}