php xml and arrays.

Associate
Joined
4 Mar 2007
Posts
315
Location
United Kingdom
Hello all, Ok so im am experimenting with xml and php never done this before, however I wish to turn each xml value into an array I can reference and later add to a db. (just for complexity xD)
I have modified some code I found on the net so far to this:

PHP:
<?php 

$file = "test.xml"; 

function contents($parser, $data){ 
    echo $data; 
} 

function startTag($parser, $data){ 
    echo "<b>"; 
} 

function endTag($parser, $data){ 
    echo "</b><br />"; 
} 

$xml_parser = xml_parser_create(); 
xml_set_element_handler($xml_parser, "startTag", "endTag"); 
xml_set_character_data_handler($xml_parser, "contents"); 
$fp = fopen($file, "r"); 
$data = fread($fp, 80000); 

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

xml_parser_free($xml_parser); 
fclose($fp); 
?>

However, how would I go about changing $data to an array. So I could then reference a certain type of value. a value such as <playername> in the array such as ['playername']?
 
I wouldn't use the old xml_parser stuff. I'd use SimpleXML.
PHP:
<?php
	try {
		$xml = file_get_contents($file);
		if (!$xml) {
			throw new Exception('Error reading ' . $file);
		}
		$x = new SimpleXMLElement($xml);
		var_dump($x); //shows the structure of the SimpleXML object, which has the xml document translated into PHP objects that are easy to iterate through and use.
	} catch (Exception $e) {
		die($e->getMessagE()); // Wouldn't use this for production code, but for a basic example it's fine.
	}
?>
 
Sorted. all works,
final question how would I go about checking xml tags like so?

<tag condition="1> as opposed to <tag condition="0">

Any ideas?
 
You can access attributes using array notation or by iterating over the elements and grabbing all the attributes into an array using the attributes() method. You need to cast the value to a string (or int or whatever) to perform comparisons if you use array access notation.

PHP:
$string = <<<XML
    <foobar>
        <foo condition="bar"  othercondition="baz" />
        <foo condition="foobar" othercondition="foobaz" />
    </foobar>
XML;


$xml = simplexml_load_string($string);

// access attributes using array notation
foreach ($xml as $element) {
    $condition = (string)$element['condition'];
}

// access attributes via iteration
foreach ($xml->foo as $foo) {
    $attributes = $foo->attributes();
    $condition = $attributes['condition'];
    $otherCondition = $attributes['othercondition'];
}
 
Last edited:
Sweet, i've done pretty much everything now, implemented class functionality too. for half my application. Only issue im getting is something to do with objects and arrays.
If I use
print_r($achievements);
It will load the large array list a small clip of it is:

Code:
achievements Object ( [file] => [sxi] => SimpleXMLIterator Object ( [privacyState] => public

However if I try to reference this using echo it won't allow me. I've tried using:

PHP:
echo $achievements->privacyState;
and
PHP:
echo $achievements['privacyState'];

but they give the error: cannot use object of type as array
 
sample of the xml and a paste of the code your using would be usefull :)

sure =)
PHP:
<?php
class achievements{
	var $file;
	var $sxi;

		function xml2array($fname){
		$this->sxi = new SimpleXmlIterator($fname, null, true);
		/*   $sxi = new SimpleXmlIterator($fname, null, true);
		  return sxiToArray($sxi); */
		}

		function sxiToArray($sxi){
		  $a = array();
		  for( $sxi->rewind(); $sxi->valid(); $sxi->next() ) {
			if(!array_key_exists($sxi->key(), $a)){
			  $a[$sxi->key()] = array();
			}
			if($sxi->hasChildren()){
			  $a[$sxi->key()][] = sxiToArray($sxi->current());
			}
			else{
			  $a[$sxi->key()][] = strval($sxi->current());
			}
		  }
		 return $a;
		}
}
?>

That is in the class file: the main is:

PHP:
<?php
$achievements = new achievements;
$catArr = new achievements;
$catArr->xml2array('test.xml');
print_r($catArr); // this works displays everything in an associative array.
echo ("stuff: ".$catArr->test); // this doesn't...
?>

XML file:

Code:
<game attr="1">
	<test>Test text</test>
	<menu="90">
		<option>1</option>
	</menu>
</game>
 
Never mind all; I have worked it out, and found a much more effective means of doing it. Thanks for all the help again!
 
Back
Top Bottom