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){
if($array['info1']!="Out Of Stock"){
return TRUE;
}
else {
return FALSE;
}
}
?>