2010-11-30 159 views
6

我有這個SimpleXML的對象:爲什麼is_array()返回false?

object(SimpleXMLElement)#176 (1) { 
["record"]=> 
array(2) { 
    [0]=> 
    object(SimpleXMLElement)#39 (2) { 
    ["f"]=> 
    array(2) { 
     [0]=> 
     string(13) "stuff" 
     [1]=> 
     string(1) "1" 
    } 
    } 
    [1]=> 
    object(SimpleXMLElement)#37 (2) { 
    ["f"]=> 
    array(2) { 
     [0]=> 
     string(13) "more stuff" 
     [1]=> 
     string(3) "90" 
    } 
    } 
} 

爲什麼is_array($對象 - >記錄)返回false?它清楚地表明它是一個數組。爲什麼我無法使用is_array檢測它?

另外,我無法使用(array)$ object-> record將其轉換爲數組。我得到這個錯誤:

Warning: It is not yet possible to assign complex types to properties

+2

永遠不要相信'的var_dump()`或。 – 2010-12-01 02:06:55

回答

5

SimpleXML節點是可以包含其他SimpleXML節點的對象。使用iterator_to_array().

+0

我接受了這個答案,因爲它允許我完成我的任務。謝謝大家的意見。 – doremi 2010-12-01 17:01:34

4

這不是一個數組。 var_dump輸出是誤導性的。試想一下:

<?php 
$string = <<<XML 
<?xml version='1.0'?> 
<foo> 
<bar>a</bar> 
<bar>b</bar> 
</foo> 
XML; 
$xml = simplexml_load_string($string); 
var_dump($xml); 
var_dump($xml->bar); 
?> 

輸出:

object(SimpleXMLElement)#1 (1) { 
    ["bar"]=> 
    array(2) { 
    [0]=> 
    string(1) "a" 
    [1]=> 
    string(1) "b" 
    } 
} 

object(SimpleXMLElement)#2 (1) { 
    [0]=> 
    string(1) "a" 
} 

你可以通過第二var_dump看到,它實際上是一個SimpleXMLElement

3

我解決了使用count()功能的問題:用SimpleXML`的print_r()`

if(count($xml) > 1) { 
    // $xml is an array... 
} 
相關問題