note 70244 deleted from ref.xml by bjori

From: Date: Mon, 09 Oct 2006 18:03:12 +0000
Subject: note 70244 deleted from ref.xml by bjori
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-118326@lists.php.net to get a copy of this message
Note Submitter: Rattus ---- Oops! My last posting had a typo and I have since decided to separate the file reading function from the xml conversion routine. EXAMPLE: -------- <?php print_r(xml2array(readXMLFile('file.xml'))); ?> FUNCTION DEFINITIONS: --------------------- <?php function readXMLFile($xmlFilename) { if (is_file($xmlFilename)) { $xml = file_get_contents($xmlFilename); // load file and remove unnecessary white-space $xml = preg_replace('@[\t\r\n]+@', '', $xml); $xml = preg_replace('@>\s+@', '>', $xml); $xml = preg_replace('@\s+<@', '<', $xml); return $xml; } return false; } function xml2array($xml) { if (!is_string($xml)) return false; $xmlary = array(); $ReElements = '/<\s*(\w+)\s*([^\/>]*)\s*(?:\/>|>(.*?)<(\/\s*\1\s*)>)/s'; $ReAttributes = '/(\w+)=(?:"|\')([^"\']*)(:?"|\')/'; preg_match_all($ReElements, $xml, $elements); $index = 0; foreach($elements[1] as $ie => $xx) { if ($attributes = trim($elements[2][$ie])) { preg_match_all ($ReAttributes, $attributes, $att); foreach ($att[1] as $ia => $yy) $xmlary["attributes"][$att[1][$ia]] = $att[2][$ia]; // all the attributes for current element are added here } $cdend = strpos($elements[3][$ie], "<"); // get text if it's combined with sub elements if ($cdend > 0) $xmlary["text"] = substr($elements[3][$ie], 0, $cdend); if (preg_match($ReElements, $elements[3][$ie])) $xmlary[$elements[1][$ie]][$index++] = xml2array ($elements[3][$ie]); else if (isset($elements[3][$ie])) $xmlary[$elements[1][$ie]] = $elements[3][$ie]; } return $xmlary; } ?>

« previous php.notes (#118326) next »