note 59097 deleted from ref.xml by bjori
| From: | bjori@php.net | Date: | Mon, 09 Oct 2006 10:52:59 +0000 |
| Subject: | note 59097 deleted from ref.xml by bjori | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-118242@lists.php.net to get a copy of this message | ||
Note Submitter: aerik at wikidweb dot com
----
Thanks Janne and zacheryph, for the fixes. I found the same problem with the regex, and did a
pretty major re-write, which you may be interested in. This works with multiple tags having the
same name, attributes, self closing tags, and text. It gets the closing tag, if there is one, so
you can figure out if you have a self closing tag or a regular tag. I think it does all the basic
stuff...
// Function xml2array
// takes an xml string and returns an array of elements
// each element is an associative array, consisting of 'name', 'test',
// possible 'attributes', sub 'elements', and closing tag if there is one.
// If there are attributes, they are also
// an associative array whose key values are the names of the attributes
// and the values are the array values
// Aerik Sylvan, Oct 27 2005
function xml2array ($xml)
{
$xmlary = array ();
if ((strlen ($xml) < 256) && is_file ($xml))
$xml = file_get_contents ($xml);
$ReElements = '/<(\w+)\s*([^\/>]*)\s*(?:\/>|>(.*?)<(\/\s*\1\s*)>)/s';
$ReAttributes = '/(\w+)=(?:"|\')([^"\']*)(:?"|\')/';
preg_match_all ($ReElements, $xml, $elements);
foreach ($elements[1] as $ie => $xx) {
$xmlary[$ie]["name"] = $elements[1][$ie];
if ( $attributes = trim($elements[2][$ie])) {
preg_match_all ($ReAttributes, $attributes, $att);
foreach ($att[1] as $ia => $xx)
// all the attributes for current element are added here
$xmlary[$ie]["attributes"][$att[1][$ia]] = $att[2][$ia];
} // if $attributes
// get text if it's combined with sub elements
$cdend = strpos($elements[3][$ie],"<");
if ($cdend > 0) {
$xmlary[$ie]["text"] = substr($elements[3][$ie],0,$cdend -1);
} // if cdend
if (preg_match ($ReElements, $elements[3][$ie])){
$xmlary[$ie]["elements"] = xml2array ($elements[3][$ie]);
}
else if (isset($elements[3][$ie])){
$xmlary[$ie]["text"] = $elements[3][$ie];
}
$xmlary[$ie]["closetag"] = $elements[4][$ie];
}//foreach ?
return $xmlary;
}