We help IT Professionals succeed at work.
Get Started

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

tseller7 asked
Last Modified: 2013-12-12
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!
	$xml = simplexml_load_file('peoples.xml');
	echo "<br />";
	//I know this is way off
	foreach($xml->PEOPLE as $key1){
		foreach($key1 as $key => $value){
			echo $key." = ".$value."<br />";
<?xml version='1.0' encoding='ISO-8859-1'?>
		<CITY>New York</CITY>
		<CITY>San Jose</CITY>

Open in new window

Watch Question
This problem has been solved!
Unlock 1 Answer and 3 Comments.
See Answer
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE