2011-06-15 127 views
0
Array ([0] => 
    SimpleXMLElement Object ([record] => 
    SimpleXMLElement Object ([f] => 
          Array ([0] => Company 
            [1] => Company 
            [2] => Mark Test 
            [3] => Intern 
            [4] => Administrative 
            [5] => Account 
            [6] => img.png 
            [7] => SimpleXMLElement Object ([@attributes] => Array ([id] => 18)) 
            [8] => SimpleXMLElement Object ([@attributes] => Array ([id] => 21)) 
            [9] => [email protected] 
            [10] => SimpleXMLElement Object ([@attributes] => Array ([id] => 178)) 
            [11] => SimpleXMLElement Object ([@attributes] => Array ([id] => 177)) 
            [12] => SimpleXMLElement Object ([@attributes] => Array ([id] => 179)) 
            [13] => SimpleXMLElement Object ([@attributes] => Array ([id] => 168))) 
          [update_id] => 12102222262043))) 

這基本上是我simplexmlobject數組,我想以某種方式只是操縱並從f元素開始取出數據。我想將公司,Mark Test,Intern等字樣存儲到數組中。我似乎無法弄清楚我是如何在PHP中使用foreach循環做到這一點的,並且這種結構非常瘋狂。麻煩存儲SimpleXMLElement對象到數組

好讓這個數據是我在代碼中getUsers()做一個API調用,這給了我一個simplexml的服務部分做了這一切的價值觀:

$xml = $getUser->getUsers(); 
$records = $xml->xpath('//records'); 

print_r($records); 
+0

所以,你要拿出後的一切,包括文檔中'F'?另外,封閉'Array'從哪裏來?你能發佈生成這個輸出的代碼嗎? – 2011-06-15 21:39:13

+0

是的我想要所有這些元素到一個不那麼複雜的數組中。 – Novazero 2011-06-15 21:41:20

+0

你可能最好使用DOMDocument而不是SimpleXML。我很樂意使用DOMDoment編寫一個例子,但是當涉及到這種類型的東西時,SimpleXML有點太麻煩了......我應該知道,我實際上用SimpleXML修復了一個數組的問題,但它不會出來直到PHP 5.4發佈。 – 2011-06-15 21:44:29

回答

1

DOM文檔類的行爲方式小比的SimpleXML在這樣的情況下更好的(當你想要做的事稍微複雜一些)......

首先加載文檔:

$dom = new DOMDocument(); 
$dom->load($filename); 

然後讓所有的<records>節點:

// Get a list of all <records> nodes which you can then loop through with foreach 
$records = $dom->getElementsByTagName('records'); 

要獲取所有<records>節點的孩子:

$allChildren = array(); 
foreach ($records as $recordSet) { 
    foreach($recordSet->childNodes as $child) { 
    $allChildren[] = $child; 
    } 
} 

現在讓我們說你想要的<first_name>第一<records>值節點:

$value = $records->item(0)->getElementsByTagName('first_name')->item(0)->nodeValue; 

請注意,getElementsByTagName的返回值是DOMNodeList s不是數組。

如果您瞭解Javascript,那麼這個類的行爲非常類似於DOM。

參見: http://www.php.net/manual/en/book.dom.php

+0

好吧,試試這個,希望事情變得更好: )感謝您的時間和精力。 – Novazero 2011-06-15 22:12:02

+0

不客氣。如果您遇到與此代碼相關的任何問題,請回復此主題,我將跳入內容並查看我能做些什麼。 – 2011-06-15 22:12:55

+0

是的工作更好,然後我期待謝謝:) – Novazero 2011-06-15 22:50:43