2012-09-07 36 views
0

這裏是XML:SimpleXMLElement文檔 - 如何在SimpleXMLElement對象中返回子屬性的值?

<Routes> 
    <Route type="source"> 
     <Table> 
      <Tablename>incoming</Tablename> 
      <Fields> 
       <Fieldsname ref="description" name="Route Name">description</Fieldsname> 
       <Fieldsname name="CID Match">cidnum</Fieldsname> 
       <Fieldsname name="DID Match">extension</Fieldsname> 
       <Fieldsname ref="dest">destination</Fieldsname> 
      </Fields> 
     </Table> 

    </Route> 
</Routes> 

然後我在PHP它實例:

$doc = new SimpleXMLElement('routingConfig.xml', null, true); 

print_r($doc->Route[0])表明這一點:

SimpleXMLElement Object 
(
    [@attributes] => Array 
     (
      [type] => source 
     ) 

    [comment] => SimpleXMLElement Object 
     (
     ) 

    [Table] => SimpleXMLElement Object 
     (
      [Tablename] => incoming 
      [comment] => SimpleXMLElement Object 
       (
       ) 

      [Fields] => SimpleXMLElement Object 
       (
        [Fieldsname] => Array 
         (
          [0] => description 
          [1] => cidnum 
          [2] => extension 
          [3] => destination 
         ) 

        [comment] => Array 
         (
          [0] => SimpleXMLElement Object 
           (
           ) 

          [1] => SimpleXMLElement Object 
           (
           ) 

         ) 

       ) 

     ) 

) 

通知根值如何有@attributes陣列。爲什麼$doc->Routes[0]->Table->Fields->Fieldsname@attributes?我知道我可以通過attributes()得到它,但是有沒有辦法讓它包含在$doc

編輯 顯然print_r()不顯示在陣列/對象的每價值,探索所有的孩子等等。也許SimpleXMLElement不會返回它,除非請求(好像它都應該存放在$doc) 。如果你這樣做print_r($doc->Route[0]->Table->Fields->Fieldsname[0]);,它返回

SimpleXMLElement Object 
(
    [@attributes] => Array 
     (
      [ref] => description 
      [name] => Route Name 
     ) 

    [0] => description 
) 

它顯示我正在尋找的數據。但是,如果我做了print_r($doc->Route[0]->Table->Field);數據不會出現。

+0

'的print_r()旨在'用於調試。如果你確定你可以通過在這些節點上調用'attributes()'來獲得attrs,爲什麼還要擔心'print_r()'? –

+0

它更是我想'$ doc'包含所有正確的價值觀,包括'attributes'兒童,而不是擔心'的print_r()'。我只是用'print_r'來顯示'$ doc'對象/數組。 – Jared

+0

你可以通過'simplexml_load_file()'加載它嗎? –

回答

1

SimpleXMLElement對象確實在PHP中一些非常先進的東西。它實現了PHP提供的許多「魔術」鉤子,以便它可以在諸如foreach()之類的東西中工作,並且被視爲像「黑匣子」一樣對待。因此,使用print_r()就會給你帶來誤導和不完整的信息。您只能在SimpleXMLElement對象上依賴print_r()(或var_dump())。

SimpleXMLElement中調試結構的方法是簡單查找您之後的元素:例如isset($xmlnode->child)等工作。所以is_array($doc->Route[0]->Table->Fields->Fieldsname)將是真實的。