note 55943 deleted from ref.xml by bjori

From: Date: Mon, 09 Oct 2006 11:12:58 +0000
Subject: note 55943 deleted from ref.xml by bjori
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-118286@lists.php.net to get a copy of this message
Note Submitter: HansP ---- Standing on the shoulders of guyemup (see below), I developed this simple parser which returns a linear array where each key is the heirarchical node name. Attributes and CDATA are both returned. <?PHP function xml2array ($name, $xml, $Echar='.', $Achar='/', $discardempty=true) { static $Result, $A, $E, $Discard; if ((strlen ($xml) < 256) && is_file ($xml)) $xml = file_get_contents ($xml); if ($name == '') { $Result = array (); $A = $Achar; $E = $Echar; $Discard = $discardempty; } $ReElements = '/<(\w+)\s*([^\/>]*)\s*(?:\/>|>(.*)<\/\s*\\1\s*>)/s'; $ReAttributes = '/(\w+)=(?:"|\')([^"\']*)(:?"|\')/'; preg_match_all ($ReElements, $xml, $elements); foreach ($elements[1] as $ie => $xx) { if ( $attributes = trim($elements[2][$ie])) { preg_match_all ($ReAttributes, $attributes, $att); foreach ($att[1] as $ia => $xx) $Result[$name.$E.$elements[1][$ie].$A.$att[1][$ia]] = $att[2][$ia]; } if (preg_match ($ReElements, $elements[3][$ie])) xml2array ($name ? $name.$E.$elements[1][$ie] : $elements[1][$ie], $elements[3][$ie]); else if (!$Discard || $elements[3][$ie]) $Result[$name.$E.$elements[1][$ie]] = $elements[3][$ie]; } return $Result; } ?> Given as input <XML> <title> Sample App </title> <version> v. 1.0</version> <window> <height>220</height> <width>420</width> </window> <parameters p1='value 1' p2='value 2'> <p3 p31='value 1 of p3'> ' value of 3 '</p3> </parameters> </XML> The output is Array ( [XML.title] => Sample App [XML.version] => v. 1.0 [XML.window.height] => 220 [XML.window.width] => 420 [XML.parameters/p1] => value 1 [XML.parameters/p2] => value 2 [XML.parameters.p3/p31] => value 1 of p3 [XML.parameters.p3] => ' value of 3 ' ) The parser is very forgiving and does not check for errors.

« previous php.notes (#118286) next »