note 83812 deleted from class.xmlreader by thiago
| From: | thiago@php.net | Date: | Wed, 12 Nov 2008 13:37:45 +0000 |
| Subject: | note 83812 deleted from class.xmlreader by thiago | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-146432@lists.php.net to get a copy of this message | ||
Note Submitter: EllisGL
----
So I need to quickly process sections of a large XML file and I came up with this really dirty class
file.
<?php
// Quick And Dirty XML to Array V 1.00
// Quick in speed, Dirty with the 2D non assoc array it makes.
// By: EllisGL 06/12/08
//
// Usuage:
// $xml = new XML_Fast_Parse($data=string, $section=string [, $callback=string][, $type=int]);
// $xml->parseIt();
//
// $data: Either a file location or string data
// $section: the section where you want to get data from
// $callback: Name of external function - this will process the array for each section
// $type: 0 for file, 1 for string data
class XML_QND
{
private $reader = "";
private $section = "";
private $callback = "";
function XML_Fast_Parse($data, $section, $callback="", $type=0)
{
$this->reader = new XMLReader();
$this->section = $section;
$this->callback = $callback;
if($type === 0)
{
// File
$this->reader->open($data);
}
else
{
// String
$this->reader->XML($data);
}
}
function parseIt()
{
while($this->reader->read())
{
if($this->reader->nodeType == 1 &&
$this->reader->localName == $this->section)
{
do
{
// Expand the rest of the data to text
$element = $this->reader->expand();
// Convert to an array
$arr = explode("\n", $element->textContent);
// Clean up the array...
foreach($arr as $key=>$val)
{
$arr[$key] = ltrim($val);
}
// Call back
$call = $this->callback;
$call($arr);
}while($this->reader->next('item_data'));
break;
}
}
return($arr);
}
}
set_time_limit(0);
function echoit($arr)
{
echo '<pre>';
print_r($arr);
echo '</pre>';
}
$data ='<?xml version="1.0" encoding="UTF-8" ?>
<DataFeeds>
<item_data>
<item_basic_data>
<item_unique_id>aaa</item_unique_id>
<item_sku>bbb</item_sku>
<item_upc>ccc</item_upc>
<item_mpn>ddd</item_mpn>
<item_brand>eee</item_brand>
</item_basic_data>
<merch_cat_list>
<merch_cat_item>
<merch_cat_name>fff</merch_cat_name>
</merch_cat_item>
<merch_cat_item>
<merch_cat_name>gggg</merch_cat_name>
</merch_cat_item>
</merch_cat_list>
</item_data>
<item_basic_data>
<item_unique_id>aaa</item_unique_id>
<item_sku>bbb</item_sku>
<item_upc>ccc</item_upc>
<item_mpn>ddd</item_mpn>
<item_brand>eee</item_brand>
</item_basic_data>
<merch_cat_list>
<merch_cat_item>
<merch_cat_name>fff</merch_cat_name>
</merch_cat_item>
<merch_cat_item>
<merch_cat_name>gggg</merch_cat_name>
</merch_cat_item>
</merch_cat_list>
</item_data>
</DataFeeds>';
$xml = new XML_QND($data, 'item_data', 'echoit', 1);
$xml->parseIt();
?>