chirs
chirs

Reputation: 35

Loop through SimpleXml object in php

I have a simpleXml object and want to read the data from the object.I am new to php.The object details are as follows.I want to read name like general and name which is inside company array i.e Korey Kay & Partners.What is the syntax for it?

SimpleXMLElement Object ( 
    [@attributes] => Array ( [type] => array ) 
    [project] => Array (  
        [0] => SimpleXMLElement Object ( 
            [created-on] => 2008-07-18 
            [id] => 2257372 
            [last-changed-on] => 2010-05-27T22:28:29Z 
            [name] => *GENERAL 
            [status] => active 
            [company] => SimpleXMLElement Object ( 
                 [id] => 406952 
                 [name] => Korey Kay & Partners 
            ) 
        )
    )
)

Upvotes: 2

Views: 1657

Answers (1)

Felix Kling
Felix Kling

Reputation: 816404

The documentation offers some examples. I think it is very well explained.

For looping you can use for or foreach.


Because it is your first question ;) In your case it would be something like:

$projects = array();
$companies = array();

foreach($xml->project as $project) {
    $projects[$project->id] = $project->name;
    $companies[$project->company->id] = $project->company->name;
    // and / or
    echo 'Project ' . $project->name . ' has ID ' . $project->id . PHP_EOL;
    echo 'Company ' . $project->company->name . ' has ID ' . $project->company->id . PHP_EOL;
}

PHP's documentation is quite good imho. For the really basic elements, they offer good examples. I very much advice you to read it!

Upvotes: 4

Related Questions