Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

parsing xml with php

Status
Not open for further replies.

axman505

Technical User
Jun 20, 2001
489
US
I have the following hunk of code:
Code:
		if ($dh = opendir($this->stylesPath)) {
			while (false !== ($file = readdir($dh))){
				if ($file !="." && $file != ".."){
					$this->styles[$i] = array();
					$this->styles[$i]['dirname'] = $file;
					
					// Import XML Here
					
					// Read in style.css
					$filename = $this->stylesPath."/".$this->styles[$i]['dirname']."/style.css";
					$fp = fopen($filename, "r");
					$contents = fread($fp, filesize($filename));
					fclose($fp);
					$this->styles[$i]['css'] = $contents;
					
					$i++;
				}
			}
       		closedir($dh);
		}

What I want to do in this loop, is read in and parse an xml file containing data at the noted position. The xml file will be formated similar to:
Code:
<info>
      <name>Myname</name>
      <author>MyAuthor</author>
</info>

I am able to parse the xml file out and print it to the screen, but I am having some difficulties trying to get these values assigned to variables. Can anyone offer any hints? Thanks!
 
What you want to look at is the DOM extension documentation on the php.net website (
This extension has a bunch of functions for creating, reading and manipulating XML documents, and it's included in the core installation of recent versions of PHP.

There's a host of functions for extracting elements, attributes and values, so just have a look at the list of functions to see what you need for the task.

Good luck!
 
Those are some great functions, however I am currently restricted to php 4, which will be troublesome. Are there any other solutions?
 
Hi,

on PHP 4.3.10 I'm ussing next functions:
Code:
function GetXMLTree ($xmldata)
{
    // we want to know if an error occurs
    ini_set ('track_errors', '1');

    $xmlreaderror = false;

    $parser = xml_parser_create ('ISO-8859-1');
    xml_parser_set_option ($parser, XML_OPTION_SKIP_WHITE, 1);
    xml_parser_set_option ($parser, XML_OPTION_CASE_FOLDING, 0);
    if (!xml_parse_into_struct ($parser, $xmldata, $vals, $index)) {
        $xmlreaderror = true;
        echo "error";
    }
    xml_parser_free ($parser);

    if (!$xmlreaderror) {
        $result = array ();
        $i = 0;
        if (isset ($vals [$i]['attributes']))
            foreach (array_keys ($vals [$i]['attributes']) as $attkey)
            $attributes [$attkey] = $vals [$i]['attributes'][$attkey];

        $result [$vals [$i]['tag']] = array_merge ($attributes, GetChildren ($vals, $i, 'open'));
    }

    ini_set ('track_errors', '0');
    return $result;
}

function GetChildren ($vals, &$i, $type)
{
    if ($type == 'complete') {
        if (isset ($vals [$i]['value']))
            return ($vals [$i]['value']);
        else
            return '';
    }

    $children = array (); // Contains node data

    /* Loop through children */
    while ($vals [++$i]['type'] != 'close') {
        $type = $vals [$i]['type'];
        // first check if we already have one and need to create an array
        if (isset ($children [$vals [$i]['tag']])) {
            if (is_array ($children [$vals [$i]['tag']])) {
                $temp = array_keys ($children [$vals [$i]['tag']]);
                // there is one of these things already and it is itself an array
                if (is_string ($temp [0])) {
                    $a = $children [$vals [$i]['tag']];
                    unset ($children [$vals [$i]['tag']]);
                    $children [$vals [$i]['tag']][0] = $a;
                }
            } else {
                $a = $children [$vals [$i]['tag']];
                unset ($children [$vals [$i]['tag']]);
                $children [$vals [$i]['tag']][0] = $a;
            }

            $children [$vals [$i]['tag']][] = GetChildren ($vals, $i, $type);
        } else
            $children [$vals [$i]['tag']] = GetChildren ($vals, $i, $type);
        // I don't think I need attributes but this is how I would do them:
        if (isset ($vals [$i]['attributes'])) {
            $attributes = array ();
            foreach (array_keys ($vals [$i]['attributes']) as $attkey)
            $attributes [$attkey] = $vals [$i]['attributes'][$attkey];
            // now check: do we already have an array or a value?
            if (isset ($children [$vals [$i]['tag']])) {
                // case where there is an attribute but no value, a complete with an attribute in other words
                if ($children [$vals [$i]['tag']] == '') {
                    unset ($children [$vals [$i]['tag']]);
                    $children [$vals [$i]['tag']] = $attributes;
                }
                // case where there is an array of identical items with attributes
                elseif (is_array ($children [$vals [$i]['tag']])) {
                    $index = count ($children [$vals [$i]['tag']]) - 1;
                    // probably also have to check here whether the individual item is also an array or not or what..
. all a bit messy
                    if ($children [$vals [$i]['tag']][$index] == '') {
                        unset ($children [$vals [$i]['tag']][$index]);
                        $children [$vals [$i]['tag']][$index] = $attributes;
                    }
                    $children [$vals [$i]['tag']][$index] = array_merge ($children [$vals [$i]['tag']][$index], $attr
ibutes);
                } else {
                    $value = $children [$vals [$i]['tag']];
                    unset ($children [$vals [$i]['tag']]);
                    $children [$vals [$i]['tag']]['value'] = $value;
                    $children [$vals [$i]['tag']] = array_merge ($children [$vals [$i]['tag']], $attributes);
                }
            } else
                $children [$vals [$i]['tag']] = $attributes;
        }
    }

    return $children;
}

As a sample, read xml from a file (the `file' could be an URL which returns an XML as Content-Type):
Code:
$contents = file_get_contents($file);

$xml_tree = GetXMLTree ($contents);
echo '<PRE>';
print_r($xml_tree);
echo '</PRE>';
And you will have an associative array in $xml_tree.


Regards,
PM

___
____
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top