note 109273 added to class.xmlreader

From: Date: Sun, 01 Jul 2012 22:50:20 +0000
Subject: note 109273 added to class.xmlreader
Groups: php.notes 
Request: Send a blank email to php-notes+get-188993@lists.php.net to get a copy of this message
This is a very basic function based on some of the code from other users below, it will find all the elements within the node $wrapperName, store them as an associative array and pass that array to the function $callback. Its useful for processing large files like product datafeeds for example where all information is enclosed within a single wrapper tag one level deep. Variables: $file - The XML file to parse. $wrapperName - The name of the parent node for each record. $callback - The callback function. $limit - The number of positive (TRUE) returns from the callback function before parsing terminates (otherwise the entire file is parsed). <?php function xmlParse($file,$wrapperName,$callback,$limit=NULL){ $xml = new XMLReader(); if(!$xml->open($file)){ die("Failed to open input file."); } $n=0; $x=0; while($xml->read()){ if($xml->nodeType==XMLReader::ELEMENT && $xml->name == $wrapperName){ while($xml->read() && $xml->name != $wrapperName){ if($xml->nodeType==XMLReader::ELEMENT){ $name = $xml->name; $xml->read(); $value = $xml->value; if(preg_match("/[^\s]/",$value)){ $subarray[$name] = $value; } } } if($limit==NULL || $x<$limit){ if($callback($subarray)){ $x++; } unset($subarray); } $n++; } } $xml->close(); } ?> Sample Usage: xmlParse($somefile,'item_data','callback'); For XML $somefile formatted as: <item_data> <info1>inf1value</info1> <info2>inf2value</info2> <info3>inf3value</info3> </item_data> will send the following array to callback function: Array( info1 => inf1value, info2 => inf2value, info3 => inf3value ) Sample Callback Function: <?php function callback($array){ //condition and action for positive validation (increments parser limit) if(/*somecondition*/){ return TRUE; } else { return FALSE; } } ?> ---- Server IP: 69.147.83.197 Probable Submitter: 176.25.144.17 ---- Manual Page -- http://www.php.net/manual/en/class.xmlreader.php Edit -- https://master.php.net/note/edit/109273 Del: integrated -- https://master.php.net/note/delete/109273/integrated Del: useless -- https://master.php.net/note/delete/109273/useless Del: bad code -- https://master.php.net/note/delete/109273/bad+code Del: spam -- https://master.php.net/note/delete/109273/spam Del: non-english -- https://master.php.net/note/delete/109273/non-english Del: in docs -- https://master.php.net/note/delete/109273/in+docs Del: other reasons-- https://master.php.net/note/delete/109273 Reject -- https://master.php.net/note/reject/109273 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#188993) next »