user1273409
user1273409

Reputation: 39

Load XML in php

I have a SimpleXMLElement Object that I want to import with PHP. But it only loop through the first row in the XML file. I also want to show the specific columm with $item->columm1 instead of show the whole row whith all it's values .

$url = 'file.xml';
$sxml = simplexml_load_file($url);

foreach($sxml->Departure->attributes() as $item)
{
    echo $item;
}

EDIT: Here is the output, notice that I have edit the orginal values with text1, text2.

SimpleXMLElement Object ( 
[Departure] => Array ( [0] => SimpleXMLElement Object ( [@attributes] => Array ( [name] => text1 [type] => text2 [stop] => text3 [time] => text4 [date] => text4 [direction] => text5 )

EDIT2: Output->

object(SimpleXMLElement)#4 (2) { ["@attributes"]=> array(6) { ["name"]=> string(6)     "text1" ["type"]=> string(3) "text2" ["stop"]=> string(12) "text3" ["time"]=> string(5) "text4" ["date"]=> string(8) "text5" ["direction"]=> string(10) "text6" } ["JourneyDetailRef"]=> object(SimpleXMLElement)#5 (1) { ["@attributes"]=> array(1) { ["ref"]=> string(125) "text7" } } } 

EDIT3: Output->

  object(SimpleXMLElement)#7 (1) { [0]=> string(6) "text1" } object(SimpleXMLElement)#8 (1) { [0]=> string(3) "text2" } object(SimpleXMLElement)#7 (1) { [0]=> string(12) "text3" } object(SimpleXMLElement)#8 (1) { [0]=> string(5) "text4" } object(SimpleXMLElement)#7 (1) { [0]=> string(8) "text5" } object(SimpleXMLElement)#8 (1) { [0]=> string(10) "text6" } 

Upvotes: 0

Views: 690

Answers (1)

Telshin
Telshin

Reputation: 340

$item has become the object. When you want to loop over the item, make sure you tell what part of the item you want to echo out to the screen.

For example:

$url = 'file.xml';
$sxml = simplexml_load_file($url);

//foreach loop
foreach($sxml->Departure as $item){
    //vardump
    var_dump($item);

    //construct next piece of code
    foreach($item->attributes() as $key => $piece){
         echo $key.' = '.$piece;
    }
}

Upvotes: 1

Related Questions