Forum Moderators: coopster

Message Too Old, No Replies

PHP/XML Loop?

Trying to create a loop to extract XML values using PHP

         

rjbearcan

12:13 am on Nov 28, 2006 (gmt 0)

10+ Year Member



I was wondering if there is a way to create a loop to extract XML values that I can store them into a MySQL database? I'm doing a website for a local sports organization and their information is structured as follows:

<Result id='1'>
<Player>Name</Player>
<League>League</League>
<Team>Team</Team>
<Position>Position</Position>
</Result>
<Result id='2'>
<Player>Name</Player>
<League>League</League>
<Team>Team</Team>
<Position>Position</Position>
</Result>

etc.

I'm not sure how to loop this to get all the values. Whatever I try either gives me a blank screen or just the first set of values.

Any suggestions?

eelixduppy

3:42 am on Nov 28, 2006 (gmt 0)



>>Whatever I try either gives me a blank screen or just the first set of values.

Do you have some code that you want us to look at or do you want to start this thing from scratch?

rjbearcan

4:41 am on Nov 28, 2006 (gmt 0)

10+ Year Member



This is the code I use to extract the values:

$url ="players.xml";
$page = file_get_contents($url);
$xml = new SimpleXMLElement($page);

$player = $xml->Result->Player;
$league = $xml->Result->League;
$team = $xml->Result->Team;
$position = $xml->Result->Position;

echo "$player<br>
$league<br>
$team<br>
$position";

I am just wondering what loop to use to get each set? I've tried for and foreach since each Result ID is unique, I'm just not sure how to set it up.

eelixduppy

11:06 am on Nov 28, 2006 (gmt 0)



Here's the loop you are looking for:

<?php
$xmlstr = <<<XML
<?xml version='1.0' standalone='yes'?>
<results>
<Result id='1'>
<Player>Name</Player>
<League>League</League>
<Team>Team</Team>
<Position>Position</Position>
</Result>
<Result id='2'>
<Player>Name2</Player>
<League>League2</League>
<Team>Team2</Team>
<Position>Position2</Position>
</Result>
</results>
XML;
$xml = new SimpleXMLElement($xmlstr);

[url=http://us2.php.net/foreach]foreach[/url]($xml->Result as $result) {
echo $result->Player.'<br/>';
}
?>

You have to love php 5's simple xml functions ;)

Now all you have left to do is append the results into a query and submit it to your database! If you need further assistance post back :)