Bonjour,
Je debute en php et j'ai voulu suivre le tutorial de phpsolutions afin
de recuperer les données du site www.weather.com qui consiste en fait a
recuperer en allant a une adresse un fichier xml contenant les données
geographiques de la ville choisi.
Il y a donc 2 etapes, tout d'abord l'acces a l'adresse dans le message
ci dessous afin de recuperer l'id de la localité. Ensuite avec cette id
on peut acceder a une autre adresse afin de recuperer les données, mais
j'ai une erreur des le debut, quand j'accede a la premiere adresse pour
recuperer l'id de la localité, je travaille sur easyPHP 1.7 avec
php_domxml d'ajouté. voici donc le message d'erreur : "
Warning : fopen(
http://xoap.weather.com/search/search?where= evreux): failed to open stream: Bad file descriptor in c:\program files\easyphp\www\weather\Weather.php on line
248 "
Voici les fichiers (desolé de la taille mais je suis au bureau et je n'ai pas acces a mon compte donc les voici)
_______________________________________________________________________
index.php :
<html>
<head>
<meta http-equiv ="Content-Type" content="text/html; charset=iso-8859-2" />
<title>weather.com</title>
<style type="text/css">
body { background-color: white; color: black; font-family: Sans-Serif; }
</style>
</head>
<?php
error_reporting(E_ALL);
//error_reporting(E_NONE);
include("Weather.php");
include("WeatherHTML.php");
define("PARTNER_ID", "1004409465");
define("KEY_ID", "7ddce928bdbf5560");
$weather = new Weather(PARTNER_ID, KEY_ID);
$weatherHTML = new WeatherHTML(PARTNER_ID, KEY_ID);
if (isset($_GET['city'])) {
$cities = $weather->findCity($_GET['city']);
if (is_array($cities)) {
echo 'Les villes suivantes
ont été trouvées :';
foreach ($cities as $key => $value) {
echo
'<li>[index.php?cityId='.$value['id'].' '.$value['city'].']</li>';
}
echo '';
} else {
echo('La recherche a
échoué. Renouveler la recherche [index.php >>]');
}
} else if (isset($_GET['cityId'])) {
if ($weatherHTML->getWeather($_GET['cityId'])) {
echo "";
$weatherHTML->getWeatherCurrent();
echo ", ";
$weatherHTML->getWeatherLocation();
echo ", ";
$weatherHTML->getWeatherUnits();
echo "
";
$result = $weatherHTML->getWeatherForecast(0);
echo 'Cliquer ici
pour relancer la recherche [index.php >>]
';
}
} else {
echo "
<form action="" method="get">";
echo "Fournir le nom de la ville : ";
echo "</form>
";
}
?>
</html>
le fichier weather.php :
<?php
error_reporting(E_ALL);
//error_reporting(E_NONE);
define("URL_WEATHER", "
http://xoap.weather.com/weather/local/ ");
define("URL_SEARCH", "
http://xoap.weather.com/search/search?where= ");
class Weather {
var $weatherXml;
var $weatherUnits;
var $weatherCurrent;
var $weatherForecast;
var $weatherLocation;
var $unit;
var $dayf;
var $location;
var $partnerId;
var $keyId;
/**
*Le constructeur de la classe Weather à son rôle consiste à paramétrer l'identifiant d'enregistrement et
* $le clef fournit par weather.com
*/
function Weather($partnerId, $keyId) {
$this->partnerId = $partnerId;
$this->keyId = $keyId;
}
/**
* Charge la météo du serveur pour une localisation ou un type définis
* d'unités et de nombre de jours. Il renseigne également les attributs adéquats à l'intérieur de la classe .
*/
function getWeather($location, $unit
'm', $dayf 1) {
$this->location = $location;
$this->unit = $unit;
if ($dayf > 10) { // la valeur
maximale de dayf est 10 à si la valeur supérieure a été communiquée, on
la place automatiquement sur 10
$this->dayf = 10;
} elseif ($dayf < 0) {
$this->dayf = 0;
} else {
$this->dayf = $dayf;
}
$options =
"?cc=*&prod=xoap&unit=".$this->unit."&dayf=".$this->dayf."&par=".$this->partnerId."&key=".$this->keyId;
if ($fp = fopen(URL_WEATHER.$this->location.$options, "r")) {
$this->weatherXml = ""; // le buffer qui reçoit la météo dans le fichier XML
while ($buffer = fread($fp, 8192)) {
$this->weatherXml .= $buffer;
}
fclose($fp);
/** décommentez la ligne ci-dessous pour visualier le contenu du fichier XML avec la météo */
// echo "".htmlentities($this->weatherXml)."
";
$xmlDoc = xmldoc($this->weatherXml);
$context = xpath_new_context($xmlDoc);
$root = $xmlDoc->root();
// charge tous les
éléments dérivés 'head' et remplit la tableau $this->weatherUnits
$locPath = '/weather/head/*';
if ($path = xpath_eval($context, $locPath)) {
$tmpArray = $path->nodeset;
foreach ($tmpArray as $key => $value) {
$this->weatherUnits[$value->name()] = $value->get_content();
}
} else {
die('Chemin "'.$locPath.'" est incorrect');
}
// charge tous les éléments
dérivés 'loc' et remplit la tableau $this->weatherLocation
$locPath = '/weather/loc/*';
if ($path = xpath_eval($context, $locPath)) {
$tmpArray = $path->nodeset;
foreach ($tmpArray as $key => $value) {
$this->weatherLocation[$value->name()] = $value->get_content();
}
} else {
die('Chemin "'.$locPath.'" est incorrect');
}
//charge les informations de
la météo courante et remplit les tableaux $this->weatherCurrent
$locPath = '/weather/cc/*'; // on charge tous les éléments dérivés 'loc'
if ($path = xpath_eval($context, $locPath)) {
$tmpArray = $path->nodeset;
foreach ($tmpArray as $key => $value) {
if (('bar' != $value->name()) AND ('wind' != $value->name()) AND
('uv' != $value->name())) {
$this->weatherCurrent[$value->name()] = $value->get_content();
}
}
} else {
die('Chemin "'.$locPath.'" est incorrect');
}
$locPath = '/weather/cc/bar/*'; // on charge tous les éléments dérivés 'loc/bar'
if ($path = xpath_eval($context, $locPath)) {
$tmpArray = $path->nodeset;
foreach ($tmpArray as $key => $value) {
$this->weatherCurrent['bar'][$value->name()] =
$value->get_content();
}
} else {
die('Chemin "'.$locPath.'" est incorrect ');
}
// on charge tous les éléments dérivés 'loc/wind'
$locPath = '/weather/cc/wind/*';
if ($path = xpath_eval($context, $locPath)) {
$tmpArray = $path->nodeset;
foreach ($tmpArray as $key => $value) {
$this->weatherCurrent['wind'][$value->name()] =
$value->get_content();
}
} else {
die('Chemin "'.$locPath.'" est incorrect');
}
// on charge tous les éléments dérivés 'loc/uv'
$locPath = '/weather/cc/uv/*';
if ($path = xpath_eval($context, $locPath)) {
$tmpArray = $path->nodeset;
foreach ($tmpArray as $key => $value) {
$this->weatherCurrent['uv'][$value->name()] =
$value->get_content();
}
} else {
die('Chemin "'.$locPath.'" est incorrect');
}
// Fin de remplissage du tableau d'informations concernant la météo courante
// si la variable qui
définit la visualisation de la météo pour les jours à venir est
définie, il s'en suit
// une recherche des éléments adéquats dans le document XML
if ($this->dayf) {
$locPath = "/weather/dayf/lsup/text()";
if ($path = xpath_eval($context, $locPath)) {
$tmpArray = $path->nodeset;
foreach ($tmpArray as $key => $value) {
$tmpLsup = $value->get_content(); //on retient dans la
variable temporaire, l'information nécessaire à l'actualisation
}
} else {
die('Chemin "'.$locPath.'" est incorrect');
}
//
on charge tous les éléments dérivés avec l'information sur les
prévisions météo des jours à venir
for ($i = 0; $i < $this->dayf; $i++) {
// tous les éléments dérivés de day
$locPath = "/weather/dayf/day[@d="$i"]/*";
if ($path = xpath_eval($context, $locPath)) {
$tmpArray = $path->nodeset;
foreach ($tmpArray as $key => $value) {
$this->weatherForecast[$i][$value->name()] =
$value->get_content();
}
$this->weatherForecast[$i]['lsup'] = $tmpLsup; // on
enregistre pour chaque jour, les informations de mise à jour
} else {
die('Chemin "'.$locPath.'"est incorrect');
}
// les attributs de l'élément day
$locPath = "/weather/dayf/day[@d="$i"]/attribute::*";
if ($path = xpath_eval($context, $locPath)) {
$tmpArray = $path->nodeset;
foreach ($tmpArray as $key => $value) {
$this->weatherForecast[$i]['info'][$value->name()] =
$value->value();
}
}
// on extrait les détails de la météo pour un jour donné à la
première partie de la journée
$locPath = "/weather/dayf/day[@d="$i"]/part[@p="d"]/*";
if ($path = xpath_eval($context, $locPath)) {
$tmpArray = $path->nodeset;
foreach ($tmpArray as $key => $value) {
$this->weatherForecast[$i]['part_d'][$value->name()] =
$value->get_content();
}
} else {
die('Chemin "'.$locPath.'" est incorrect');
}
// les détails concernant le vent - la première partie de la
journée
$this->weatherForecast[$i]['part_d']['wind'] = array();
$locPath = "/weather/dayf/day[@d="$i"]/part[@p="d"]/wind/*";
if ($path = xpath_eval($context, $locPath)) {
$tmpArray = $path->nodeset;
foreach ($tmpArray as $key => $value) {
$this->weatherForecast[$i]['part_d']['wind'][$value->name()] =
$value->get_content();
}
} else {
die('Chemin "'.$locPath.'" est incorrect');
}
// on extrait les détails de prévisions météo - la seconde partie de la
journée
$locPath = "/weather/dayf/day[@d="$i"]/part[@p="n"]/*";
if ($path = xpath_eval($context, $locPath)) {
$tmpArray = $path->nodeset;
foreach ($tmpArray as $key => $value) {
$this->weatherForecast[$i]['part_n'][$value->name()] =
$value->get_content();
}
} else {
die('Chemin "'.$locPath.'"est incorrect');
}
// les détails concernant le vent pour un jour donné - la seconde
partie de la journée
$this->weatherForecast[$i]['part_n']['wind'] = array();
$locPath = "/weather/dayf/day[@d="$i"]/part[@p="n"]/wind/*";
if ($path = xpath_eval($context, $locPath)) {
$tmpArray = $path->nodeset;
foreach ($tmpArray as $key => $value) {
$this->weatherForecast[$i]['part_n']['wind'][$value->name()] =
$value->get_content();
}
} else {
die('Chemin "'.$locPath.'" est incorrect');
}
}
}
return true;
} else {
return false;
}
} // fin de méthode getWeather()
/**
*Méthode qui retourne le contenu relatif à la prévision météo choisie dans le tableau d'inforamtions
*/
function getWeatherLocation() {
return $this->weatherLocation;
}
/**
*Méthode qui retourne le contenu relatif aux unités employées chargé dans le tableau d'informations
*/
function getWeatherUnits() {
return $this->weatherUnits;
}
/**
*Méthode qui retourne le contenu relatif aux prévisions météo pour le jour en cours dans le tableau.
*/
function getWeatherCurrent() {
return $this->weatherCurrent;
}
/**
*Méthode qui retourne le contenu relatif aux prévisions météo pour le jour indiqué chargé dans le tableau
*/
function getWeatherForecast($day) {
return $this->weatherForecast[$day];
}
/**
*Méthode qui recherche le code pour le nom de ville indiquée
*/
function findCity($city) {
if ($this->fp = fopen(URL_SEARCH.$city, "r")) {
$cities =
""; // le
buffer pour le fichier XML que l'on est en train de charger
while ($bufor = fread($this->fp, 8192)) {
$cities .= $bufor;
}
fclose($this->fp);
/** décommentez à la ligne ci-dessous pour visualiser le contenu
du fichier XML avec les informations concernant les villes */
// echo "".htmlentities($cities)."
";
$xmlDoc = xmldoc($cities);
$context = xpath_new_context($xmlDoc);
$root = $xmlDoc->root();
$locPath =
'/search/*'; // charge
tous les éléments dérivés 'search'
if ($path = xpath_eval($context, $locPath)) {
$tmpArray = $path->nodeset;
$i = 0;
foreach ($tmpArray as $key => $value) {
$citiesA[$i]['city'] = $value->get_content();
$i++;
}
} else {
die('Chemin "'.$locPath.'" est incorrect');
}
$root = $xmlDoc->root();
$locPath =
'/search/loc/@*'; // charge tous les attributs des
éléments 'loc'
if ($path = xpath_eval($context, $locPath)) {
$tmpArray = $path->nodeset;
$i = 0;
foreach ($tmpArray as $key => $value) {
if ('id' == $value->name()) {
$citiesA[$i][$value->name()] = $value->value();
} else {
$citiesA[$i][$value->name()] = $value->value();
$i++;
}
}
} else {
return false; // aucun attribut n'
a été trouvé pour 'loc', on retourne donc NULL
}
return $citiesA;
} else {
return
false; //
si le fichier n'a pas été ouvert, on retourne NULL
}
} // fin de la méthode findCity()
}
?>
_______________________________________________________________________
et enfin weatherHTML.php :
<?php
error_reporting(E_ALL);
//error_reporting(E_NONE);
define("IMAGE_PATH", "img/");
define("IMAGE_SIZE", "128x128/");
require_once("Weather.php");
/**
* La classe WeatherHTMLhérite de la classe Weather.
* Conformément à l'original, cette dernière comporte les méthodes étendues des données que l'on affiche à l'écran.
* Elles sont adéquatement formatées et contiennent les options supplémentaires sous forme
* de fonction JavaScript.
* De même, on peut créer par exemple la classe WeatherWML qui va hériter
* de la classe Weather - cependant au lieu de créer le code HTML,
celle-ci va créer le code WML pour les applications
* mobiles.
*/
class WeatherHTML extends Weather {
/**
*Le constructeur de la classe WeatherHTML. Il appelle le constructeur original de la classe
* Par rapport à la classe source, il ne contient aucun nouveau paramètre
*/
function WeatherHTML ($partnerId, $keyId) {
$this->Weather($partnerId, $keyId);
}
/**
*Méthode qui affiche les informations, quant à la localisation,
sous forme de tableau. Il retourne également le tableau associatif
* avec toutes les données concernant la localisation.
*/
function getWeatherLocation() {
echo "\";
foreach ($this->weatherLocation as $key => $value) {
echo \"----
";
switch ($key) {
case 'dnam':
echo "Latitude :";
break;
case 'tm':
echo "Longitude :";
break;
case 'lat':
echo "Largeur géographique:";
break;
case 'lon':
echo "Longeur géographique:";
break;
case 'sunr':
echo "Levée du soleil:";
break;
case 'suns':
echo "Coucher du soleil:";
break;
case 'zone':
echo "Fuseau horaire:";
break;
}
echo ", $value, \";
}
echo "
";
return Weather::getWeatherLocation();
}
/**
* Méthode qui affiche les informations formatées concernant les unités.
*/
function getWeatherUnits() {
echo "\";
foreach ($this->weatherUnits as $key => $value) {
echo \"----
";
switch ($key) {
case 'locale':
echo "Langue du document :";
break;
case 'form':
echo "Format du document :";
break;
case 'ut':
echo "Température :";
break;
case 'ud':
echo "Distance :";
break;
case 'us':
echo "Vitesse :";
break;
case 'up':
echo "Précipitations :";
break;
case 'ur':
echo "Pression atmosphérique:";
break;
}
echo ", $value, \";
}
echo "
";
return Weather::getWeatherUnits();
}
function getWeatherCurrent() {
echo "<script type="text/javascript">";
echo "function showDetail() {\n";
echo "var noweOkno = open('', 'Weather Detail',
'width=400, height=250, status=no, toolbar=no, menubar=no,
scrollbar=no, location=no');\n";
echo "noweOkno.document.writeln('";
echo "\";
foreach ($this->weatherCurrent as $key => $value) {
switch ($key) {
case 'lsup':
echo \"----
";
echo " Date de mise à jour :";
break;
case 'obst':
echo "----, \";
echo \"Localisation :\";
break;
case 'tmp':
echo \"----
";
echo "Température :";
break;
case 'flik':
echo "----, \";
echo \"Température ressentie :\";
break;
case 't':
echo \"----
";
echo "Conditions climatiques :";
break;
case 'hmid':
echo "----, \";
echo \"Humidité :\";
break;
case 'vis':
echo \"----
";
echo "Visibilité :";
break;
case 'dewp':
echo "----, \";
echo \"Rosée :\";
break;
case 'bar':
echo \"----
";
echo "Pression atmosphérique :";
break;
case 'wind':
echo "----, \";
echo \"Vent :\";
break;
case 'uv':
echo \"----
";
echo "UV :";
break;
case 'icon':
break;
}
switch ($key) {
case 'bar':
echo ", ";
foreach ($value as $key1 => $value1) {
echo $value1." ";
}
echo ", \";
break;
case 'wind':
echo \"</td>";
foreach ($value as $key1 => $value1) {
echo $value1." ";
}
echo ", \";
break;
case 'uv':
echo \"</td>";
foreach ($value as $key1 => $value1) {
echo $value1." ";
}
echo ", \";
break;
case 'icon':
break;
default:
echo \"</td>$value, \";
break;
}
}
echo "
');\n";
echo "newWindow.document.writeln('
');";
echo "\n}\n";
echo "</script>";
echo "\";
echo \"----
weatherCurrent['icon'].".png\"
onClick=\"javascript:showDetail();\" />, ".
$this->weatherCurrent['obst']."
".$this->weatherCurrent['lsup'].", \";
echo \"----
température, ".
$this->weatherCurrent['tmp'].", \";
echo \"----
pression atmosphérique, ".
$this->weatherCurrent['bar']['r']."
".$this->weatherUnits['up'].", \";
echo \"----
humidité, ".
$this->weatherCurrent['hmid'].", \";
echo \"----
vent, ".
$this->weatherCurrent['wind']['s']." ".
$this->weatherUnits['us']." ".
$this->weatherCurrent['wind']['t'].", \";
echo "
";
return Weather::getWeatherCurrent();
}
}
?>
_______________________________________________________________________
Encore desolé de la longueur de ce post
Afficher la suite