Jump to content

Quick XML foreach question


Haighy

Recommended Posts

i am parsing through xml and want to know when i am at the end of a given 'Product' object ie when at </Product> he is my code $ParsedXml = simplexml_load_string($response); foreach($ParsedXml->Product as $current)( if (isset($current->name)) ( $name = $current->name, ) ...etc... ) I want to know when i am at the end of that Product object so i can write a line into a dabase before going through to the next one

Link to comment
Share on other sites

Using the count(), you can get the total number of child elements of a particular node (e.g. all elements inside "Product"). In addition to that, at the foreach, you can request getting the posistion of the current node as a key

foreach($ParsedXml->Product as $position => $current)

Within the foreach, simply check if ($position < $count), and act accordingly.

Link to comment
Share on other sites

Errr.... is that a question or statement?If statement... yes... so what? count() would detect that number.If it's a question... come on, do I need to spell out the code?

$count = $ParsedXml->count();foreach($ParsedXml->Product as $position => $current) {if ($position < $count) {//Last node}}

Link to comment
Share on other sites

If you knew, you'd just write the number. You need to use the count() function instead exactly becase you don't know, and the number is dynamic.

Link to comment
Share on other sites

ahh sorry - I understand now. I did not see this line in your example $count = $ParsedXml->count(); Is it possible to put this count statement inside the foreach loop? each Product could have a different number of child nodes

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...