decode XML in PHP

  • 1
  • Question
  • Updated 5 years ago
Hello!

I have tried the php example to read json:


<?php
$json_string = file_get_contents("http://api.wunderground.com/api/df4536d06b16e344/geolookup/condition/q/IA/Cedar_Rapids.json");
$parsed_json = json_decode($json_string);
$location = $parsed_json->{'location'}->{'city'};
$temp_f = $parsed_json->{'current_observation'}->{'temp_f'};
echo "Current temperature in ${location} is: ${temp_f}\n";
?>

and it works on my local server
but it does not work on my website because php version is 5.1.xxx and json decode need 5.2

would it be possible to have same example but for xml decoding instead of json ?
this example is very simple and easy to understand to me !

(it's the one found here: http://www.wunderground.com/weather/a... )
Photo of wysiwyg31

wysiwyg31

  • 3 Posts
  • 0 Reply Likes

Posted 5 years ago

  • 1
Photo of afelicioni

afelicioni

  • 227 Posts
  • 43 Reply Likes
You could query stackoverflow or similar to catch a broad choice of code that provides or uses an xml dom parser.

If you need it quick, see first the package available at http://simplehtmldom.sourceforge.net/
I have used it for little projects since months (in fact... years) and it comes handy to use.

See some usage example at http://net.tutsplus.com/tutorials/php...

Enjoy!
Photo of wysiwyg31

wysiwyg31

  • 3 Posts
  • 0 Reply Likes
Hello,
thank you for your answer!
In the mean time, I tried to follow a couple of tutorial and I have done this
I do not understand everything but it works for me :-)


$dom = new DomDocument();
$dom->load("cond.xml");
$current_observation = $dom->getElementsByTagName("current_observation");
echo'icon:[';
foreach($current_observation as $ua) {
$icon = $ua->getElementsByTagName( "icon" );
echo $icon->item(0)->nodeValue . "]\n";
}
echo'icon_url:[';
foreach($current_observation as $ua) {
$icon_url = $ua->getElementsByTagName( "icon_url" );
echo $icon_url->item(0)->nodeValue . "]\n";
}


Output looks like this:
icon:[mostlycloudy] icon_url:[http://icons-ak.wxug.com/i/c/k/nt_mos...]

I used a local file (cond.xml) for testing but it should work with api link (maybe with an additionnal line) between new domdocument and load command.
Photo of afelicioni

afelicioni

  • 227 Posts
  • 43 Reply Likes
well done!