note 55943 added to ref.xml
| From: | HansP at osu1 dot php dot net | Date: | Thu, 18 Aug 2005 13:55:11 +0000 |
| Subject: | note 55943 added to ref.xml | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-93840@lists.php.net to get a copy of this message | ||
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.
----
Manual Page -- http://www.php.net/manual/en/ref.xml.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+55943
Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+55943&report=yes&reason=added+to+the+manual
Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+55943&report=yes&reason=bad+code
Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+55943&report=yes&reason=spam
Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+55943&report=yes&reason=useless
Delete: non-english -- http://master.php.net/manage/user-notes.php?action=delete+55943&report=yes&reason=non-english
Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+55943&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+55943&report=yes
Search -- http://master.php.net/manage/user-notes.php