Forgot username/password? Don't have an account?
Login with Facebook
Home » Courses » 02Hero XML » foreach
Subscribe for updates.
* New to us? log in with Facebook and get a free day pass


We now look at how to write a basic loop in PHP. Generally, our XML document may have several instances of the same element category. This element list is organized as just that %u2013 a list %u2013 and the individual elements need to be processed one at a time. The PHP language provides a looping construct - "foreach" - which can be used to step through the list of element instances just like an array is indexed using integer variables to obtain specific element values.

A practical example will clear things up, if there's any doubt remaining as to how foreach looping constructs work! Here's a real-life example:

Consider a bar that's one of a chain. Suppose each bar has a specification in XML,so that it can be read and processed by a computer program for maintaining drink records. An XML document that specifies the structure of a particular bar might look like:

<?xml version="1.0" encoding="UTF-8" ?>


<drink id="Martini" base="gin" />

< drink id="Sex_on_the_Beach" base="peach_creme," />

< drink id="Fuzzy_Navel" base="schnapps" />

< drink id="Vodka_Collins" base="vodka" />


<name type="Red" id="Merlot" />

<name type="White" id="Riesling" />

<name type="White" id="Chardonnay" />



Let us now write a PHP script with source code that loads this bar.xml document, iterates through the "duplicate" elements (which have different attribute values) and prints out information that is useful for auditing purposes. Have a look at the following sample:


$bar = simplexml_load_file("bar.xml");

foreach($bar->drink as $drink){

echo $drink['id'] . 'is made from:' . $drink['base'];


foreach($bar->wine as $wine){

foreach($wine->name as $name){

echo $name['type'];




The organization of the PHP code segment is intuitive and can easily be seen to match with the XML structure explained above it. Such looping constructs are extremely useful for progammers because they don't need to know the exact number of element in an XML document. The program that processes the XML document simply indexes the element list (of the same category) just as an array of values is read by a conventional program. Arbitrarily-sized XML documents can be easily processed without much ado. And such code structure is also easy to read, since loops are fundamental constructs of all programming languages.

Got A Question?

'I love being Prime'

Have a question but don't want to ask it publicly? If you are a prime member just ask right here and we will get back to you within 48 hours. Not prime yet? no worries you can ask publicly below.

Act now while we have available seating

Our on line school is private, affordable and interactive with trainer support.
Act now save your seat before someone else takes yours.
Act now