note 109275 deleted from intro.xmlreader by salathe

From: Date: Mon, 21 Jul 2014 12:34:16 +0000
Subject: note 109275 deleted from intro.xmlreader by salathe
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-200000@lists.php.net to get a copy of this message
Note Submitter: dale ---- This is a very basic function based on some of the code from other users, 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 about each record is enclosed within a single wrapper tag. For Example: <product> <name>someproduct</name> <brand>somebrand</brand> <price>someprice</price> </product> <product> <name>someproduct</name> <brand>somebrand</brand> <price>someprice</price> </product> 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> <item_data> <info1>inf1value</info1> <info2>inf2value</info2> <info3>inf3value</info3> </item_data> <item_data> <info1>inf1value</info1> <info2>inf2value</info2> <info3>inf3value</info3> </item_data> will send the following array to the callback function for each item where it can be processed and added to a database etc.: Array( info1 => inf1value, info2 => inf2value, info3 => inf3value ) Sample Callback Function: <?php function callback($array){ //condition and action for positive validation (increments parser limit) if($array['info1']!="Out Of Stock"){ /*add to database*/ return TRUE; } else { return FALSE; } } ?>

« previous php.notes (#200000) next »