...

View Full Version : trouble parsing xml using SimpleXMLElement



shadkeene
03-03-2012, 11:05 PM
Here's my script:


<?php

ini_set('display_errors', 1);

error_reporting(E_ALL|E_STRICT);

// script: csv_to_xml.php
// description: retrieves csv file of recreation site data and converts to xml
// altered to grab snow depth from tripcheck xml data
// author: Shad Keene
// date: 3/2/2012


$file = "http://www.greenandtheblue.com/weather/roadtest.xml";


$data = @file_get_contents($file);
$xml_file_data = new SimpleXMLElement($data);
echo '<pre>';
print_r($xml_file_data);
echo '</pre>';



$i = 0;

while ($xml_file_data->weatherReports->weatherReport[$i]->location->locationName != ''){

if (preg_match("/LK OF THE WOODS/", $xml_file_data->weatherReports->weatherReport[$i]->location->locationName)) {
echo"found lake of the woods";
}

$i++;


}



?>

I'm trying to get locationname tags to key in on certain locations, but it's giving errors. I've tried some different things, but nothing has worked. I'm just trying to get wired in to the way this xml is organized and how to access the various elements. I've taken a look at a few tutorials, but they seemed too basic.

Thanks for any help!

S

Inigoesdr
03-04-2012, 05:39 PM
Here is how you could do it with xPath:


<?php

$file = 'http://www.greenandtheblue.com/weather/roadtest.xml';
$data = file_get_contents($file);
$xml_file_data = new SimpleXMLElement($data);

echo '<pre>';

$result = $xml_file_data->xpath('/informationResponse/responseGroups/responseGroup/weatherReports/weatherReport/location[locationName = "LK OF THE WOODS"]/../*');

echo 'Location: ' . (string) $result[1]->locationName . "\n";
echo 'currTemp: ' . (string) $result[2] . "\n";
echo 'highTemp: ' . (string) $result[3] . "\n";
echo 'lowTemp: ' . (string) $result[4] . "\n";

echo 'snowDepth: ' . (string) $result[6] . "\n";
echo 'snowOffRoad: ' . (string) $result[7] . "\n";
echo 'drivingRestrictions: ' . trim((string) $result[8]) . "\n";

echo '</pre>';
Outputs:

Location: LK OF THE WOODS
currTemp: -6.1
highTemp: 1001
lowTemp: 1001
snowDepth: 3001
snowOffRoad: 96.52
drivingRestrictions: Carry chains or traction tires.

tracknut
03-04-2012, 08:32 PM
This might be useful in terms of easier to read:


$result = $xml_file_data->xpath('/informationResponse/responseGroups/responseGroup/weatherReports/weatherReport/location[locationName = "LK OF THE WOODS"]/..');
echo 'Location: ' .$result[0]->location->locationName . "\n";
echo 'currTemp: ' .$result[0]->currTemp. "\n";
echo 'highTemp: ' .$result[0]->highTemp . "\n";
echo 'lowTemp: ' .$result[0]->lowTemp. "\n";
echo 'drivingRestrictions: ' . trim($result[0]->drivingRestrictions) . "\n";
echo '</pre>';


Dave



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum