We help IT Professionals succeed at work.
Get Started

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

tseller7
tseller7 asked
on
1,752 Views
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!
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

Comment
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