Student
Student

Reputation: 27

While looping through a xml file I'm getting unexpected line break in the output

The php Code even if the node does not have children, it is executing only the <br> part of the second foreach loop, thus output is spaces, then if the are childnodes, it output the result. Tried put an if statement before the 2nd foreach loop, still not working!

<?php

$xmlDoc = simplexml_load_file("contact.xml");

foreach ($xmlDoc->children() as $books) {
    if ($books->Firstname == "John") {
        echo $books->Firstname, "<br>";
        echo $books->Lastname, "<br>";
        echo $books->Nickname, "<br>";
        foreach ($books->children() as $book) {
            echo $book->CourseName, "<br>";
            echo $book->ID, "<br>";
        }
    }
}

?>

Result:

John
Cruse
Tom




Software
484887

^ Why do I get these extra 3 line breaks and how can I get rid of them?

Upvotes: 0

Views: 80

Answers (2)

Rizier123
Rizier123

Reputation: 59701

Just change your second foreach header from:

foreach($books->children() as $book){    
              //^^^^^^^^^^

to this:

foreach($books->Course as $book){
              //^^^^^^

Because with your old foreach header you looped through all child's of PersonalInfo which was: Firstname, Lastname, Nickname, Course and only the last one (Course) had a CourseName and an ID in it, so the other ones just printed 2x break line tags.

Upvotes: 1

Sagar
Sagar

Reputation: 647

Use $books->count(); It gives you count of children. Note: SimpleXMLElement::children() returns a node object no matter if the current node has children or not. Use count() on the return value to see if there are any children. As of PHP 5.3.0, SimpleXMLElement::count() may be used instead.

Upvotes: 0

Related Questions