麻烦将SimpleXMLElement对象存储到数组中

时间:2011-06-15 21:36:15

标签: php arrays object simplexml

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] => emailtest@gmail.com 
                                     [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元素开始取出数据。我希望像公司,马克测试,实习生一样存储到一个数组中。我似乎无法弄清楚我是如何用php中的foreach循环来做这个的,而且结构很疯狂。

为了得到这些数据的所有值,我在我的代码的一部分中做了这个,其中getUsers()对一个给我一个simplexml的服务进行api调用:

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

print_r($records);

1 个答案:

答案 0 :(得分:1)

在这种情况下(当你想做一些稍微复杂的事情时),DOMDocument类的行为比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不是数组。

如果您了解Javascript,那么这个类的行为非常类似于DOM是Javascript。

另见: http://www.php.net/manual/en/book.dom.php