0

I have a array which it reads its cells from a xml file,i wrote it by "for" but now because i don't know how many node i have i wanna to write this loop in a way that it start and finish up to end of xml file.my code with for is:

$description=array();

for($i=0;$i<2;$i++)
{
$description[$i]=read_xml_node("dscription",$i);
}

and my xml file:

<eth0>
<description>WAN</description>      
</eth0>
<eth1>
<description>LAN</description>      
</eth1>

in this code i must know "2",but i wanna to know a way that doesn't need to know "2".

4
  • What XML parser/API are you using? Commented Jun 12, 2013 at 8:56
  • This is pretty trivial using SimpleXML: php.net/manual/en/simplexml.examples-basic.php Commented Jun 12, 2013 at 8:58
  • First of all, there's no native function in PHP called read_xml_node so you have to show us either the code of it or the library in which the function exists. Secondly, you spelled description wrong (dscription). Commented Jun 12, 2013 at 8:58
  • DOM,i use my function to read it, my code works correctly,my problem is:if i don't know how many description are in my xml that for will work correctly. Commented Jun 12, 2013 at 9:00

3 Answers 3

1

i am not sure what kind of parser you are using, but it is very easy with simplexml, so i put together some sample code using simplexml.

something like this should do the trick:

$xmlstr = <<<XML
<?xml version='1.0' standalone='yes'?>
<node>
<eth0>
<description>WAN</description>      
</eth0>
<eth1>
<description>LAN</description>      
</eth1>
</node>
XML;

$xml = new SimpleXMLElement($xmlstr);

foreach ($xml as $xmlnode) {
 foreach ($xmlnode as $description) {
  echo $description . " ";
 }
}

output:

WAN LAN  
Sign up to request clarification or add additional context in comments.

Comments

0
$length = count($description);
for ($i = 0; $i < $length; $i++) {
  print $description[$i];
}

Comments

0

The parser you use might allow you to use a while loop which will return false when it has reached the end of the XML document. For example:

while ($node = $xml->read_next_node($mydoc)) {
    //Do whatever...
}

If none exists, you can try using count() as the second parameter of your for loop. It returns the length of an array you specify. For example:

for ($i = 0; $i < count($myarray); $i++) {
    //Do whatever...
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.