Here is a quick and dirty solution. Let me know how it goes!
<?php
/*
Ok, here goes. I'll give an example using SAX. You could easily do this using DOM as well. I use a little bit of OOP, but you can easily do this just using straight functions.
--Make sure that you have the appropriate extensions installed (ie, XML, expat, etc)
*/
class StringParser
{
//the original string
var $stringXML;
//the final array as you wanted it
var $finalArray;
//the xml parser object
var $parser;
//the current tag that is being parsed
var $currentTag;
//the current data that is being parsed
var $currentData;
/**
* Constructor - Accepts a string (like above) as the only parameter.
*
*/
function StringParser($stringParam)
{
$this->stringXML = $stringParam;
//create the parser
$this->parser = xml_parser_create();
//tell php to look for the xml handlers in this class
xml_set_object($this->parser, &$this);
xml_set_element_handler($this->parser,"startElementHandler", "endElementHandler");
//register the character data parser
xml_set_character_data_handler($this->parser, "cdataHandler");
//turn off case folding
xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, 0);
//parse the XML document
xml_parse($this->parser, $this->stringXML);
//free the XML parser
xml_parser_free($this->parser);
}
/**
* startElementHandler
*
* @param parserParam The XML parser object
* @param nameParam The current XML tag being parsed
* @param attribsParam The attributes for the current tag (in your case none)
*/
function startElementHandler($parserParam, $nameParam, $attribsParam)
{
//echo $nameParam;
$this->currentTag = $nameParam;
}
/**
* endElementHandler
*
* @param parserParam The XML parser object
* @param nameParam The current XML tag being parsed
*/
function endElementHandler($parserParam, $nameParam)
{
//add this xml tag to the array if it isn't the document tag
if(strcmp($nameParam, "document") != 0)
{
$this->addElementToArray("<" . $nameParam . ">" . $this->currentData . "</" . $nameParam . ">");
}
//reset the data
$this->currentData = "";
}
/**
* cdataHandler
*
* @param parserParam The XML parser object
* @param dataParam The current Data
*/
function cdataHandler($parserParam, $dataParam)
{
$this->currentData .= $dataParam;
}
/**
* addElementToArray
*
* @param stringParam The line to be added to the array
*/
function addElementToArray($stringParam)
{
$this->finalArray[] = $stringParam;
}
/**
* printFinalArray --simply prints the final results
*
*
*/
function printFinalArray()
{
for($i = 0; $i < count($this->finalArray); $i++)
{
echo $this->finalArray[$i] . "\n";
}
}
}
$string = "<document><tag1>sdfsdfs</tag1><tag2>asdfsdfs</tag2></document>";
$foo = new StringParser($string);
//echo count($foo->finalArray);
$foo->printFinalArray();
?>
risto wrote:
well I' don't understand it at all 🙂 I read the documentation, but I can't apply it! 🙁