note 52230 deleted from ref.xml by bjori

From: Date: Mon, 09 Oct 2006 11:14:34 +0000
Subject: note 52230 deleted from ref.xml by bjori
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-118310@lists.php.net to get a copy of this message
Note Submitter: mv at brazil dot com ---- here a exemple to parse XML file to an PHP array and PHP array to XML. <? $file = "menu_items.xml"; /** * Get contents from XML file and insert into an array * * @param string $file * @return mixed */ function xml2php($file) { $xml_parser = xml_parser_create(); if (!($fp = fopen($file, "r"))) { die("unable to open XML"); } $contents = fread($fp, filesize($file)); fclose($fp); xml_parse_into_struct($xml_parser, $contents, $arr_vals); xml_parser_free($xml_parser); return $arr_vals; } /** * Convert php array to XML * * @param mixed $array_haystack * @return string */ function php2xml($array_haystack) { $xml = "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>\n"; if ((!empty($array_haystack)) AND (is_array($array_haystack))) { foreach ($array_haystack as $xml_key => $xml_value) { switch ($xml_value["type"]) { case "open": $xml .= str_repeat("\t", $xml_value["level"] - 1); $xml .= "<" . strtolower($xml_value["tag"]); $xml .= (!isset($xml_value["attributes"]))? ">\n": false; break; case "complete": $xml .= str_repeat("\t", $xml_value["level"] - 1); $xml .= "<" . strtolower($xml_value["tag"]); $xml .= (!isset($xml_value["attributes"]))? ">\n": false; break; case "close": $xml .= str_repeat("\t", $xml_value["level"] - 1); $xml .= "</" . strtolower($xml_value["tag"]); $xml .= (!isset($xml_value["attributes"]))? ">\n": false; break; default: break; } if (isset($xml_value["attributes"])) { foreach ($xml_value["attributes"] as $atribute_key => $atribute_value) { $xml .= sprintf(' %s="%s"', strtolower($atribute_key), $atribute_value); } $xml .= ($xml_value["type"] == "complete")? " />\n": ">\n"; } } } return $xml; } /** * Output content as XML * * @param string $content */ function output_xml($content) { header("Content-Type: application/xml; charset=ISO-8859-1"); header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); header("Last-Modified: ". gmdate("D, d M Y H:i:s") ." GMT"); header("Cache-Control: no-store, no-cache, must-revalidate"); header("Cache-Control: post-check=0, pre-check=0", false); header("Pragma: no-cache"); print $content; } $arr_xml = xml2php($file); $xml = php2xml($arr_xml); output_xml($xml); ?>

« previous php.notes (#118310) next »