2012-10-31 53 views
1

我在我的php簡單的xml對象上遇到了麻煩。xml到php陣列問題

我在日誌下面的XML數據

SimpleXMLElement Object 
(
    [@attributes] => Array 
     (
      [title] => test 
      [scanner] => Data 
      [id] => WordData 
      [position] => 1800 
      [error] => false 
      [num] => 6 
     ) 

    [subpod] => Array 
     (
      [0] => SimpleXMLElement Object 
       (
        [@attributes] => Array 
         (
          [title] => Surnames 
         ) 

        [plaintext] => Common (US population: 650 people, white: 63% | black: 35%) 
        [img] => SimpleXMLElement Object 
         (
          [@attributes] => Array 
           (

            [alt] => Common (US population: 650 people, white: 63% | black: 35%) 
            [title] => Common (US population: 650 people, white: 63% | black: 35%) 
            [width] => 349 
            [height] => 18 
           ) 

         ) 

       ) 

      [1] => SimpleXMLElement Object 
       (
        [@attributes] => Array 
         (
          [title] => Cities 
         ) 

        [plaintext] => Littleton Common (Massachusetts, 2789 people) 
        [img] => SimpleXMLElement Object 
         (
          [@attributes] => Array 
           (

            [alt] => Littleton Common (Massachusetts, 2789 people) 
            [title] => Littleton Common (Massachusetts, 2789 people) 
            [width] => 287 
            [height] => 18 
           ) 

         ) 

       ) 

      [2] => SimpleXMLElement Object 
       (
        [@attributes] => Array 
         (
          [title] => Buildings 
         ) 

        [plaintext] => Rotunda on Woolwich Common (London, Greater London) 
        [img] => SimpleXMLElement Object 
         (
          [@attributes] => Array 
           (

            [alt] => Rotunda on Woolwich Common (London, Greater London) 
            [title] => Rotunda on Woolwich Common (London, Greater London) 
            [width] => 356 
            [height] => 18 
           ) 

         ) 

       ) 
       .....more simpleXmlElement object 
     ) 
) 

我的PHP varible $xmlObj = SimpleXMLElement Object但是當我有以下

if (is_array($xmlObj->subpod)){ 
    echo 'is array';  
}else { 
    echo 'not array'; 
} 

輸出總是「不陣」,我想我的代碼echo'is array'

我以爲$xmlObj->subpod是一個數組。 當我測試$xmlObj->subpod[0]->plaintext時,它實際上會返回字符串。 我不知道如何解決這個問題。誰能幫忙?

+0

當你var_dump($ xmlObj-> subpod);'? – AlienWebguy

+0

你的報價在哪裏? –

回答

2

如果你是var_dump($xmlObj->subpod),你會發現它仍然是一個SimpleXMLElement對象。但是,它仍然可以被稱爲數組。 (見注this example之後,這暗示了這個類實現ArrayAccess,即使類的文檔沒有。)

正確的方法來檢查這個結構將使用SimpleXMLElement::count()

if ($xmlObj->subpod->count() > 0) { ... } 

編輯:你的問題的輸出大概是從print_r,這有時在其輸出中是非常沒有幫助的(例如告訴你一些事情是一個數組,當它不是)。改爲使用var_dump,因爲它通常對調試更有用。唯一需要注意的是,你不能看到SimpleXMLElement對象的整個嵌套對象結構!

2

裏面SimpleXMLElement Object一切都是SimpleXMLElement Object,print_r的和後續代碼var_dump有時說謊陣列 - 他們是穿越的對象,但你可以,如果他們數組對它們執行的大部分操作。如果你堅持有純數組,你可以將這個節點轉換爲數組:

$subpod = (array)$xmlObj->subpod;