[thelist] php & xml, counting elements

Jeremy Weiss eccentric.one at gmail.com
Sun Dec 13 23:00:00 CST 2009


On a project I'm working on I need to loop through some XML that's retrieved
from a 3rd party API and display it in a form so that changes can be made
and resubmitted to the 3rd party site. Unfortunately, the XML isn't
structured 'right' in my opinion.  There's one section that could have
infinite items, but instead of being nested they just modify the key like
so:

<userTemplate_19222_1>ABC</userTemplate_19222_1>
<userTemplate_19222_2>123</userTemplate_19222_2>
<userTemplate_19222_3>XYZ</userTemplate_19222_3>

So each record is differentiated by the _X at the end of the tag. I need to
find a way to determine how many records there are so that I can construct
the form to display them all. I tried to count them using 

$fields = simplexml_load_string($stuff);

for ($i = 1; ; $i++) {
	$exp = $fields->root->userTemplate_19222_{$i};
	if (empty($exp)) {
		$top = $i--;
		break;
	}
}

The idea was to then use $top in another loop to build the form. But $top
always equals 1 for some reason.

Anyone have any suggestions? Is there a better way to go about this?


Thanks,
-jeremy



More information about the thelist mailing list