Avatar of tseller7
tseller7
 asked on

How to foreach simplexml, SimpleXMLElement Object, xml file using php

I am trying to go through an xml file. I first loaded the XML file as an SimpleXMLElement object. I am trying to go through each value. How do I go through the values using foreach()?

When I run the print_r it gives me:
SimpleXMLElement Object ( [PERSON] => SimpleXMLElement Object ( [NAME] => Jake [CITY] => Tempe [AGE] => 22 ) )

So, I would like to go through using foreach() and get the name, city and age of the person.

I attached the code for the xml file and the php file

Thank you!
PHP FILE:
 
<html>
<head></head>
<body>
<?php
 
	$xml = simplexml_load_file('peoples.xml');
	
 
	print_r($xml);
	
	echo "<br />";
	//I know this is way off
	foreach($xml->PEOPLE as $key1){
		foreach($key1 as $key => $value){
			echo $key." = ".$value."<br />";
		}
	} 
 
?>
</body>
</html>
 
XML FILE:
 
<?xml version='1.0' encoding='ISO-8859-1'?>
<PEOPLE>
	<PERSON>
		<NAME>Jake</NAME>
		<CITY>Tempe</CITY>
		<AGE>22</AGE>
	</PERSON>
	<PERSON>
		<NAME>Rick</NAME>
		<CITY>New York</CITY>
		<AGE>34</AGE>
	</PERSON>
	<PERSON>
		<NAME>Dan</NAME>
		<CITY>San Jose</CITY>
		<AGE>19</AGE>
	</PERSON>
</PEOPLE>

Open in new window

PHPXML

Avatar of undefined
Last Comment
tseller7

8/22/2022 - Mon
ASKER CERTIFIED SOLUTION
Graceful_Penguin

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
pkoops

If you have an SimpleXMLObject, you can use xpath to search for all of your persons.

http://de.php.net/manual/en/function.simplexml-element-xpath.php
$xml = simplexml_load_file('peoples.xml');
$result = $xml->xpath('/people/person');
foreach($result as $person) {
// make some action here
print_r($person);
}

Open in new window

tseller7

ASKER
God, that was easy! How did I miss it. Thanks so much!
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes