Xml parsing - drilling down

Hi

I’m parsing an xml feed (at the moment using the script below) and I want to echo out the data inside tags but only if it’s not more xml to parse. This is easy in the contents functions I just need to strip space and check the length is greater than 0 but how do I stop the starttag and endtag from echoing as well? Any ideas on how to do this?

I know I can do this using a xml to array parsing function but then I have to parse the array again to get it into the format I want which seems silly (and twice as long).

Thanks in advance
Garrett

<?php

$file  = "file.xml";

//functions to pase the xml content
function contents($parser, $data)
{
    //strip all excess white space and echo data if it's longer than 0
    echo $data;
}

function starttag($parser, $data)
{
    echo $data.":";
}

function endtag($parser, $data)
{
    echo "<br />";
}
//functions to pase the xml content



//create a parser object
$xml_parser = xml_parser_create();

//put this in front and after each bit of data
xml_set_element_handler($xml_parser, "starttag", "endtag");

//parse the contents
xml_set_character_data_handler($xml_parser, "contents");

//open the file with read permissions
$fp = fopen($file, "r");

//read the file
$data = fread($fp, 80000);

//parse or die
if(!(xml_parse($xml_parser, $data, feof($fp))))
{
    die("Error on line " . xml_get_current_line_number($xml_parser));
}

//free the parser
xml_parser_free($xml_parser);

//close the file
fclose($fp);

?>

You would… probably find it easier using SimpleXML rather than the XML class…if only for the fact that you can check if(count($node->children()) == 0)

yes choice with php 5 is suddenly overwhelming and I was wondering was this the best way, I used to use string functions which worked well but was long. I’ll have a look at SimpleXML.

thanks
Garrett

Many thanks Starlion, nudge in the better direction much appreciated, this is efficient and feels familiar as it’s the same as traversing a multi-dimensinal array.

Garrett


<?php

//function to traverse multi-dimensional xml
function traverse($data)
{
    //loop through data seperating out key and value
    foreach ($data as $key => $value)
    {
        //if value has no children
        if (count($value->children()) == 0)
        {
            //display it
            echo $key.":".$value."<br />";
        }
        else
        {
            //else call the function again
            traverse($value);
        }
    }
}


//file to parse
$file  = "index.xml";

//load it
$data = simplexml_load_file($file);

//call function
traverse($data);

?>

Btw-


$data = simplexml_load_file($file);
$iter = new RecursiveIteratorIterator(
    new SimpleXMLIterator($data)
);
foreach ($iter as $key => $value) {
    echo $key.":".$value."<br />";
}

RecursiveIteratorIterator has a default mode of LEAVES_ONLY, which is what you’re doing when checking if children is 0.

wow shorter still! thanks for the tip. :slight_smile:

Garrett