logo

:: XML Parsing in PHP ::

XML parsing is made very simple in PHP5 with the availability of the SimpleXML extension. This extension is enabled by default since PHP 5.1.2. If you are using an older version of PHP without SimpleXML, you will need to reconfigure your PHP with --enable-simplexml option.

If you have your XML data in a file, to parse your XML you load the XML to a SimpleXMLElement object by simply calling the simplexml_load_file() function. If your XML is in a string variable, use simplexml_load_string() instead.

:: Example - Weather Forecast Using Google API ::

<?php
$city 
"melbourne";

$xml simplexml_load_file("http://www.google.com/ig/api?weather=".urlencode($city));

foreach (
$xml->weather as $item)
{
    foreach(
$item->forecast_conditions as $forecast)
    {
        echo 
"<div>\n";
        echo 
"<img src='http://www.google.com/" .$forecast->icon['data'] . "'   alt='".$forecast->condition['data']."' />\n";
        echo 
"<b>".$forecast->day_of_week['data']."</b> ";
        echo 
fahrenheitToCelcius($forecast->low['data'])."&deg; - " fahrenheitToCelcius($forecast->high['data']) . "&deg;C<br />";
        echo 
"\n</div>\n";
    }
}


// Converts temperature from Fahrenheit to Celcius
function fahrenheitToCelcius ($f)
{
    
$c = ($f 32) * 5.0 9;
    return 
round($c);
}

?>
© Copyright php-etc.com 8525. Please contact the webmaster for all enquiries.