note 102973 added to class.simplexmliterator

From: Date: Thu, 17 Mar 2011 18:14:57 +0000
Subject: note 102973 added to class.simplexmliterator
Groups: php.notes 
Request: Send a blank email to php-notes+get-177963@lists.php.net to get a copy of this message
Here's a simple function to convert an XML string to an array - <?php // PHP5.3 and above only function parse($str) { $f = function($iter) { foreach($iter as $key=>$val) $arr[$key][] = ($iter->hasChildren())? call_user_func (__FUNCTION__, $val) : strval($val); return $arr; }; return $f(new SimpleXmlIterator($str, null)); } ?> PHP 5.2 and below do not have anonymous functions. But you can create a helper function to achieve the same thing - <?php function parse($str) { return parseHelper(new SimpleXmlIterator($str, null)); } function parseHelper($iter) { foreach($iter as $key=>$val) $arr[$key][] = ($iter->hasChildren())? call_user_func (__FUNCTION__, $val) : strval($val); return $arr; } ?> Using it is straightforward enough - <?php $xml = ' <movies> <movie>abcd</movie> <movie>efgh</movie> <movie>hijk</movie> </movies>'; var_dump(parse($xml)); ?> This will output - array 'movie' => array 0 => string 'abcd' (length=4) 1 => string 'efgh' (length=4) 2 => string 'hijk' (length=4) ---- Server IP: 69.147.83.197 Probable Submitter: 64.100.144.8 (proxied: 64.100.125.37) ---- Manual Page -- http://www.php.net/manual/en/class.simplexmliterator.php Edit -- https://master.php.net/note/edit/102973 Del: integrated -- https://master.php.net/note/delete/102973/integrated Del: useless -- https://master.php.net/note/delete/102973/useless Del: bad code -- https://master.php.net/note/delete/102973/bad+code Del: spam -- https://master.php.net/note/delete/102973/spam Del: non-english -- https://master.php.net/note/delete/102973/non-english Del: in docs -- https://master.php.net/note/delete/102973/in+docs Del: other reasons-- https://master.php.net/note/delete/102973 Reject -- https://master.php.net/note/reject/102973 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#177963) next »