Saturday, 24 August 2013

foreach issue with if/else retrieving xml data

foreach issue with if/else retrieving xml data

I've been looking for answers to my problem on SW but no luck so far..so
here it goes. I'm writing a form where the user can search for items that
are written in a xml file on the server...the search function works pretty
well; the form sends the values to a php file and using simplexml it
retrieves the data from the xml file using a foreach with an if/else
statement. However, when there is no item found on the xml file, that's
where the issue comes.
Here's my php:
<?php
$zip = $_POST['zip'];
$id = $_POST['id'];
$xml = simplexml_load_file("lista.xml");
foreach ($xml as $entry){
if (($entry->zipCode == $zip) && ($entry->id == $id)){
?>
<p>Id: <?php echo $entry->id;?></p>
<p>Zip: <?php echo $entry->zipCode;?></p>
<p>Item: <?php echo $entry->item;?></p>
<?php
}
else {echo 'nothing found';}
}?>
And this is my xml:
<?xml version="1.0" encoding="utf-8"?>
<entries>
<entry>
<id>id1</id>
<zipCode>zip1</zipCode>
<item>1</item>
</entry>
<entry>
<id>id2</id>
<zipCode>zip2</zipCode>
<item>2</item>
</entry>
<entry>
<id>id3</id>
<zipCode>zip3</zipCode>
<item>3</item>
</entry>
</entries>
The issue is that instead of showing 'nothing found' just once if there is
no item within the whole xml file, it shows 'nothing found' in every entry
that does not have the search query on it. So, for instance, if $zip =
zip4 and $id = id4 the answer is:
nothing found
nothing found
nothing found
instead of just one 'nothing found'
What's the correct way of writing that piece of code?? Thanks everyone in
advance!!!

No comments:

Post a Comment