1.11M Members

Simple XML Parsing With PHP?

 
0
 

hi guys, how are you?

I hope someone can help me with this as its been bugging me all day, and I'm sure there is a very simple explanation.

Basically, what I have at the moment is this:-

$ip = ($_SERVER["REMOTE_ADDR"]);
$xml = file_get_contents("http://xxxxxxxxxxxxxx);

This returns me the following in XML:

<?xml version="1.0" encoding="UTF-8"?>
<Response>
	<statusCode>OK</statusCode>
	<statusMessage></statusMessage>
	<ipAddress>2.99.203.40</ipAddress>
	<countryCode>UK</countryCode>
	<countryName>UNITED KINGDOM</countryName>
</Response>

What I want to be able to do now, is store the countryCode in a variable called $country.

Surely it can't be so difficult??? I'm so stuck. I've tried this, and think i'm on the right track, but its not working.

$xmlparse = simplexml_load_file($xml);
$country=$xmlparse->countryCode[0];
// show country
echo $country;

Any help is much appreciated.

Regards
David

 
0
 

$country=$xmlparse->Response->countryCode;

 
0
 

$country=$xmlparse->Response->countryCode;

Thanks chris, i tried that, now getting an error:-

Warning: simplexml_load_file() [function.simplexml-load-file]: I/O warning : failed to load external entity "<?xml version="1.0" encoding="UTF-8"?> <Response> <statusCode>OK</statusCode> <statusMessage></statusMessage> <ipAddress>2.99.203.40</ipAddress> <countryCode>UK</countryCode> <countryName>UNITED KINGDOM</countryName> </Response>" in /home/rankwar2/public_html/index.php on line 6

 
0
 

Are you sure the server is running PHP 5?

 
0
 

Hi,

You only use countryCode[0], when there are multiple countryCode .

for example,

<?xml version="1.0" encoding="UTF-8"?>
<Response>
<statusCode>OK</statusCode>
<statusMessage></statusMessage>
<ipAddress>2.99.203.40</ipAddress>
<countryCode>UK</countryCode>
<countryCode>UK1</countryCode>
<countryCode>UK2</countryCode>
<countryName>UNITED KINGDOM</countryName>
</Response>

If I want to parse the coutryCode for UK, my script should be something like this.Assuming that the above file is named xml.xml.


!ADDED LATER ON EDIT!

$xml = "xml.xml";
$xml = @simplexml_load_file($xml);

foreach($xml as $items){

$country = $items->countryCode[0];

echo $country;
}

If you need more example, please visit my previous posts in this forum... I got a lot about xml parsing.

You
This article has been dead for over six months: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: