php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #37817 bad foreach loop the second time with simple xml
Submitted: 2006-06-15 12:24 UTC Modified: 2006-12-31 21:19 UTC
Votes:4
Avg. Score:3.8 ± 0.4
Reproduced:4 of 4 (100.0%)
Same Version:4 (100.0%)
Same OS:0 (0.0%)
From: ecervetti at ch-hyeres dot fr Assigned: helly (profile)
Status: Not a bug Package: SimpleXML related
PHP Version: 5.1.4 OS: Linux mandriva 2006
Private report: No CVE-ID: None
View Developer Edit
Welcome! If you don't have a Git account, you can't do anything here.
If you reported this bug, you can edit this bug over here.
(description)
Block user comment
Status: Assign to:
Package:
Bug Type:
Summary:
From: ecervetti at ch-hyeres dot fr
New email:
PHP Version: OS:

 

 [2006-06-15 12:24 UTC] ecervetti at ch-hyeres dot fr
Description:
------------
I try to access a particular element of xml data with the
foreach($xml->name_of_element ....) syntax.

But I don't know if this element exists.

When the element don't exists, no problem the first time;
It don't goes inside the loop.

But If I call the same loop a second time, it goes inside the loop, as if the element exists.


Reproduce code:
---------------
 $string = "<data><typebal1>pim</typebal1><typebal2>poom</typebal2></data>";


 $xml = simplexml_load_string($string);

 foreach($xml->typebal3 as $bal) {
 	print "<br />I should not be here<br />";	
 }

 foreach($xml->typebal3 as $bal) {
 	print "<br />I should either not be here<br />";	
 }

 //this script renders "I should either not be here"

Expected result:
----------------
this script should not print anything

Actual result:
--------------
this script renders "I should either not be here"

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2006-06-19 08:02 UTC] mike@php.net
Verified with 5.2
 [2006-08-08 17:09 UTC] ale at estudionemo dot com
I've found a post in the mailing list about this issue:
http://www.mail-archive.com/php-general@lists.php.net/msg190494.html
It says that "it's not a bug, it's a feature".

It behaves in the same way in PHP 5.1.4 under Solaris 10 and  Ubuntu 6.06.
 [2006-12-31 21:19 UTC] iliaa@php.net
Thank you for taking the time to write to us, but this is not
a bug. Please double-check the documentation available at
http://www.php.net/manual/ and the instructions on how to report
a bug at http://bugs.php.net/how-to-report.php

When you access an non-existenet element SimpleXML creates a 
node in the DOM tree. This node is then present for future 
iterations of the DOM tree. 

To avoid creating the DOM node, use the isset($xml->typebal3) 
code to check for its presence. This will allow you to 
determine if the node exists and not create if it does not. 
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Thu Dec 26 13:01:30 2024 UTC