note 82661 added to ref.simplexml

From: Date: Mon, 21 Apr 2008 06:39:55 +0000
Subject: note 82661 added to ref.simplexml
Groups: php.notes 
Request: Send a blank email to php-notes+get-138597@lists.php.net to get a copy of this message
I found simpleXML to be useful only in cases where the XML was extremely small, otherwise the server would run out of memory (I suspect there is a memory leak or something?). So while searching for alternative parsers, I decided to try a simpler approach. I don't know how this compares with cpu usage, but I know it works with large XML structures. This is more a manual method, but it works for me since I always know what structure of data I will be receiving. Essentially I just preg_match() unique nodes to find the values I am looking for, or I preg_match_all to find multiple nodes. This puts the results in an array and I can then process this data as I please. I was unhappy though, that preg_match_all() stores the data twice (requiring twice the memory), one array for all the full pattern matches, and one array for all the sub pattern matches. You could probably write your own function that overcame this. But for now this works for me, and I hope it saves someone else some time as well. // SAMPLE XML <RETS ReplyCode="0" ReplyText="Operation Successful"> <COUNT Records="14" /> <DELIMITER value="09" /> <COLUMNS>PropertyID</COLUMNS> <DATA>521897</DATA> <DATA>677208</DATA> <DATA>686037</DATA> </RETS> <?PHP // SAMPLE FUNCTION function parse_xml($xml) { // GET DELIMITER (single instance) $match_res = preg_match('/<DELIMITER value ?= ?"(.*)" ?\/>/', $xml, $matches); if(!empty($matches[1])) { $results["delimiter"] = chr($matches[1]); } else { // DEFAULT DELIMITER $results["delimiter"] = "\t"; } unset($match_res, $matches); // GET MULTIPLE DATA NODES (multiple instances) $results["data_count"] = preg_match_all("/<DATA>(.*)<\/DATA>/", $xml, $matches); // GET MATCHES OF SUB PATTERN, DISCARD THE REST $results["data"]=$matches[1]; unset($match_res, $matches); // UNSET XML TO SAVE MEMORY (should unset outside the function as well) unset($xml); // RETURN RESULTS ARRAY return $results; } ?> ---- Server IP: 212.199.163.191 Probable Submitter: 79.179.235.181 ---- Manual Page -- http://www.php.net/manual/en/ref.simplexml.php Edit -- https://master.php.net/note/edit/82661 Del: integrated -- https://master.php.net/note/delete/82661/integrated Del: useless -- https://master.php.net/note/delete/82661/useless Del: bad code -- https://master.php.net/note/delete/82661/bad+code Del: spam -- https://master.php.net/note/delete/82661/spam Del: non-english -- https://master.php.net/note/delete/82661/non-english Del: in docs -- https://master.php.net/note/delete/82661/in+docs Del: other reasons-- https://master.php.net/note/delete/82661 Reject -- https://master.php.net/note/reject/82661 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#138597) next »