Problem: I want to get all locations from a database and encase them all in the <loc> tag, the following code puts each location in a <loc> tag, leading to several <loc> when I only need one. I know it’s doing this because it’s inside a loop (the simpleXML part), but have no idea how to solve it.
if($r7){ //$r7 = If query was successfull..
while($row = mysqli_fetch_array($r7, MYSQLI_ASSOC)){
$convXML_from_loc = $convXML_from->addChild('loc',$row['location']);
}
}
If I take it out of the loop, it just puts the first location in the database there (iirc).
The alternative to this is just echo "<xml>"; which I thought was bad practice, because nothing would have parent and child elements, and everything would be on the same level.
I would appreciate any guidance on this issue, as well as links to any relevant information on this subject.
Regards.
EDIT: If it was unclear, I need to put them all within a single loc tag, like <loc>Row 1, Row 2</loc>. At the moment it’s giving <loc>Row 1</loc><loc>Row 2</loc>.
You have a while loop that iterates over every row. You’re going to do whatever is in the loop for as many times as there are rows. So you will be making as many
<loc>elements as there are rows, one for each row.The solution is to generate a string that contains all of the row data inside of the while loop, and then add the
<loc>element with that string outside of the loop. This causesaddChild()to be called only one time, thus creating only one<loc>element.