How to load xml's data by simplexml?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
GiaTuan
Forum Newbie
Posts: 14
Joined: Sat Oct 01, 2011 1:19 am

How to load xml's data by simplexml?

Post by GiaTuan »

I need to get col from xml:

Code: Select all

<titles>
     <row>
          <col>0</col><col>4</col>
     </row>
     <row>
          <col>1</col><col>41</col>
     </row>
     <row>
          <col>2</col><col>42</col>
     </row>
</titles>
result:

Code: Select all

row 0:
col 0:0 col1:4
row 1:
col 0:1 col1:41
row 2:
col 0:2 col1:42
I tried:

Code: Select all

$file="info.xml";
$xml = simplexml_load_file($file);
$count=count($xml->row);
foreach($xml->children() as $child) {
	$data="$child->col";
	echo "col=$data<br/>";
}
col=0
col=1
col=2
I just get first col
User avatar
social_experiment
DevNet Master
Posts: 2793
Joined: Sun Feb 15, 2009 11:08 am
Location: .za

Re: How to load xml's data by simplexml?

Post by social_experiment »

Try the snippet below

Code: Select all

<?php
foreach($xml->children() as $child) {
        $data= $child['col'];
        echo "col=$data<br/>";
}
?>
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering
pbs
Forum Contributor
Posts: 230
Joined: Fri Nov 07, 2008 5:31 am
Location: Nashik, India
Contact:

Re: How to load xml's data by simplexml?

Post by pbs »

Also try this

Code: Select all

$count= count($xml->row);
for($i=0;$i<$count;$i++)
{
	$row = $xml->row[$i];
	echo $row->col[0]."==".$row->col[1]."<br>";
}
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: How to load xml's data by simplexml?

Post by requinix »

What pbs is getting at is that if you just look at $child->col you'll only get the first element. You have to treat it like an array (eg, use an offset or a loop) if you want to get all the elements.
Post Reply