Tutorial: Leer clima de Yahoo! tiempo con PHP

  • righteous_trespasser
  • Scuffle
  • Genius
  • Avatar de Usuario
  • Registrado: Mar 12, 2007
  • Mensajes: 6228
  • Loc: South-Africa
  • Status: Offline

Nota Mayo 12th, 2008, 4:34 am

Introducción


Muchas veces se ve que el clima de leer páginas web de un feed RSS en otro sitio, aquí malos mostrar cómo leer el clima en su sitio de Yahoo! Weathers RSS feed con PHP.

Dónde obtener el código XML de


Para leer el tiempo de Yahoo! tiempo, enviar una solicitud a Yahoo! que es como sigue:
Código: [ Select ]
http://weather.yahooapis.com/forecastrss?p=SFXX0044&u=c

donde p es el código de localización...En este tutorial estoy usando "Pretoria, Sudáfrica" (de donde soy), y como usted puede ver el código de ubicación es SFXX0044, tengo esto desde http://weather.yahoo.com y yo configuro para mi ubicación, y el código se encuentra entonces en la dirección...Alternativamente, si usted vive en los EE.UU. sólo puede utilizar el código postal donde está. A continuación, en "U" es la unidad en la que el tiempo se debe mostrar, elegí "C" para C, pero también puedes elegir la opción "f" para Fahrenheit.

Lo que el XML parece


He creado esta layut de lo que la respuesta XML parece que se volvió de Yahoo! El Tiempo:
Código: [ Select ]
<channel>
    <title>
    <link></link>
    <description></description>
    <language></language>
    <lastBuildDate></lastBuildDate>
    <ttl></ttl>
    <yweather:location city region country />
    <yweather:units temperature distance pressure speed />
    <yweather:wind chill direction speed />
    <yweather:atmosphere humidity visibility pressure rising />
    <yweather:astronomy sunrise sunset />
    <image>
        <title></title>
        <width></width>
        <height></height>
        <link></link>
        <url></url>
    </image>
    <item>
        <title></title>
        <geo:lat></geo:lat>
        <geo:long></geo:long>
        <link></link>
        <pubDate></pubDate>
        <yweather:condition text code temp date>
        <description></description>
        <yweather:forecast day date low high text code />
        <yweather:forecast day date low high text code />
        <guid Ispermalink></guid>
    </item>
</channel>
  1. <channel>
  2.     <title>
  3.     <link></link>
  4.     <description></description>
  5.     <language></language>
  6.     <lastBuildDate></lastBuildDate>
  7.     <ttl></ttl>
  8.     <yweather:location city region country />
  9.     <yweather:units temperature distance pressure speed />
  10.     <yweather:wind chill direction speed />
  11.     <yweather:atmosphere humidity visibility pressure rising />
  12.     <yweather:astronomy sunrise sunset />
  13.     <image>
  14.         <title></title>
  15.         <width></width>
  16.         <height></height>
  17.         <link></link>
  18.         <url></url>
  19.     </image>
  20.     <item>
  21.         <title></title>
  22.         <geo:lat></geo:lat>
  23.         <geo:long></geo:long>
  24.         <link></link>
  25.         <pubDate></pubDate>
  26.         <yweather:condition text code temp date>
  27.         <description></description>
  28.         <yweather:forecast day date low high text code />
  29.         <yweather:forecast day date low high text code />
  30.         <guid Ispermalink></guid>
  31.     </item>
  32. </channel>

Como puede ver, nuestro "root" elemento se denomina "canal", y debajo de eso tenemos también otros elementos, el único elemento que eant ir de aquí es la siguiente:
    channel-> item-> description
Así que permite echar un vistazo al código que vamos a utilizar:

El código


Yo voy a mostrar el código con comentarios en el medio para que pueda ver lo que estoy haciendo
PHP Código: [ Select ]
<?php
//I am using the DOM(Document Object Model) library to read the entire XML document into memory first.
$doc = new DOMDocument();
$doc->load('http://weather.yahooapis.com/forecastrss?p=SFXX0044&u=c');
//now I get all elements inside this document with the following name "channel", this is the 'root'
$channel = $doc->getElementsByTagName("channel");
//now I go through each item withing $channel
foreach($channel as $chnl)
{
//I then find the 'item' element inside that loop
$item = $chnl->getElementsByTagName("item");
foreach($item as $itemgotten)
{
//now I search within '$item' for the element "description"
$describe = $itemgotten->getElementsByTagName("description");
//once I find it I create a variable named "$description" and assign the value of the Element to it
$description = $describe->item(0)->nodeValue;
//and display it on-screen
echo $description;
}
}
?>
  1. <?php
  2. //I am using the DOM(Document Object Model) library to read the entire XML document into memory first.
  3. $doc = new DOMDocument();
  4. $doc->load('http://weather.yahooapis.com/forecastrss?p=SFXX0044&u=c');
  5. //now I get all elements inside this document with the following name "channel", this is the 'root'
  6. $channel = $doc->getElementsByTagName("channel");
  7. //now I go through each item withing $channel
  8. foreach($channel as $chnl)
  9. {
  10. //I then find the 'item' element inside that loop
  11. $item = $chnl->getElementsByTagName("item");
  12. foreach($item as $itemgotten)
  13. {
  14. //now I search within '$item' for the element "description"
  15. $describe = $itemgotten->getElementsByTagName("description");
  16. //once I find it I create a variable named "$description" and assign the value of the Element to it
  17. $description = $describe->item(0)->nodeValue;
  18. //and display it on-screen
  19. echo $description;
  20. }
  21. }
  22. ?>

http://ph81luc.net46.net/weather.php

He probado también con otro sitio web y no recibir ningún resultado la ejecución de esta página. Que la razón por la que el lugar que "Hola palabra" texto en el archivo; para fines de ensayo;
  • Bogey
  • Bogey
  • Genius
  • Avatar de Usuario
  • Registrado: Jul 14, 2005
  • Mensajes: 8211
  • Loc: USA
  • Status: Offline

Nota Noviembre 27th, 2008, 10:19 am

Tengo todo perfecto. Esto es lo que tengo en mi archivo.

Código: [ Select ]
<?php
//I am using the DOM(Document Object Model) library to read the entire XML document into memory first.
$doc = new DOMDocument();
$doc->load('http://weather.yahooapis.com/forecastrss?p=SFXX0044&u=c');
//now I get all elements inside this document with the following name "channel", this is the 'root'
$channel = $doc->getElementsByTagName("channel");
//now I go through each item withing $channel
foreach($channel as $chnl)
{
//I then find the 'item' element inside that loop
$item = $chnl->getElementsByTagName("item");
foreach($item as $itemgotten)
{
//now I search within '$item' for the element "description"
$describe = $itemgotten->getElementsByTagName("description");
//once I find it I create a variable named "$description" and assign the value of the Element to it
$description = $describe->item(0)->nodeValue;
//and display it on-screen
echo $description;
}
}
?>
  1. <?php
  2. //I am using the DOM(Document Object Model) library to read the entire XML document into memory first.
  3. $doc = new DOMDocument();
  4. $doc->load('http://weather.yahooapis.com/forecastrss?p=SFXX0044&u=c');
  5. //now I get all elements inside this document with the following name "channel", this is the 'root'
  6. $channel = $doc->getElementsByTagName("channel");
  7. //now I go through each item withing $channel
  8. foreach($channel as $chnl)
  9. {
  10. //I then find the 'item' element inside that loop
  11. $item = $chnl->getElementsByTagName("item");
  12. foreach($item as $itemgotten)
  13. {
  14. //now I search within '$item' for the element "description"
  15. $describe = $itemgotten->getElementsByTagName("description");
  16. //once I find it I create a variable named "$description" and assign the value of the Element to it
  17. $description = $describe->item(0)->nodeValue;
  18. //and display it on-screen
  19. echo $description;
  20. }
  21. }
  22. ?>


Exactamente como es la forma en righteous_trespasser lo tiene en su tutorial.
"Bring forth therefore fruits meet for repentance:" Matthew 3:8
  • ashleyquick
  • Born
  • Born
  • No Avatar
  • Registrado: Nov 20, 2008
  • Mensajes: 1
  • Status: Offline

Nota Diciembre 10th, 2008, 7:27 pm

Hola!

Parece como si con los piensos, se obtiene "ahora", hoy y mañana las previsiones. ¿Sabe si THERES una manera de recuperar el día después de "mañana", de manera que hay tres días de las previsiones? IVE espera en la página de desarrolladores de Yahoo para su tiempo de alimentación y no puedo discernir si esto es posible.

Gracias!
Ashley
  • righteous_trespasser
  • Scuffle
  • Genius
  • Avatar de Usuario
  • Registrado: Mar 12, 2007
  • Mensajes: 6228
  • Loc: South-Africa
  • Status: Offline

Nota Diciembre 11th, 2008, 12:32 am

Lamentablemente no, el feed RSS sólo contiene las condiciones meteorológicas para el día de hoy y de mañana.
Let's leave all our *plum* where it is and go live in the jungle ...
  • smith21
  • Born
  • Born
  • No Avatar
  • Registrado: Ene 02, 2009
  • Mensajes: 2
  • Status: Offline

Nota Enero 2nd, 2009, 3:33 am

Gracias hombre, es realmente una gran información ya que esta es una muy buena para ayudar a pensar a nadie con su ways.so de acuerdo con mi buen trabajo y gracias de nuevo.
  • smoogdog
  • Born
  • Born
  • No Avatar
  • Registrado: Feb 05, 2009
  • Mensajes: 1
  • Loc: Honolulu, Hawaii
  • Status: Offline

Nota Febrero 5th, 2009, 2:02 am

El código funciona perfectamente, pero ¿cómo iba a ir sobre la limitación de la información devuelta por lo que sólo pueden mostrar las condiciones actuales?
  • robin8cham
  • Born
  • Born
  • No Avatar
  • Registrado: May 20, 2009
  • Mensajes: 1
  • Status: Offline

Nota Mayo 20th, 2009, 4:01 pm

Suministrados utilizando el código PHP, obtener Error de análisis: la sintaxis error, inesperado en T_DNUMBER / homepages/1/d252457728/htdocs/newweather.php en la línea 3, donde la línea 3 = $ doc = new DOMDocument ();

Por favor.

Robin
  • righteous_trespasser
  • Scuffle
  • Genius
  • Avatar de Usuario
  • Registrado: Mar 12, 2007
  • Mensajes: 6228
  • Loc: South-Africa
  • Status: Offline

Nota Mayo 21st, 2009, 11:35 pm

Realmente no puedo ver la razón por la que le dará un error, eso no es algo sólo eso supone dar un error. Tal vez sea porque no tiene el "domxml" extensión instalada para PHP...
Let's leave all our *plum* where it is and go live in the jungle ...
  • arifbata
  • Born
  • Born
  • No Avatar
  • Registrado: May 23, 2009
  • Mensajes: 2
  • Status: Offline

Nota Mayo 23rd, 2009, 5:25 pm

Hola

En realidad tengo un proyecto en el que necesito para mostrar la situación meteorológica actual. Ahora la pregunta es como en el "righteous_trespasser" su justa tutorial que muestra el clima de una ciudad a la vez. Lo que necesito es que tengo un mapa del mundo y cuando el usuario seleccione una ciudad de un marcador se coloca en el mapa de la ciudad y que cuando se hace clic en el marcador debe mostrar el tiempo de esa ciudad. Como decir si hay un marcador en Sidney, debería mostrar el tiempo de Sidney. Espero que se haya obtenido mi pregunta.

Sugerir, por favor,
Thanx mucho.
  • arifbata
  • Born
  • Born
  • No Avatar
  • Registrado: May 23, 2009
  • Mensajes: 2
  • Status: Offline

Nota Mayo 23rd, 2009, 5:28 pm

Hola Robin,

el error que usted está recibiendo es según mi conocimiento se debe a los números de línea. Usted podría tener un código de pegado aquí para que su archivo se compone de números de línea. Eliminar el número de línea y espero que su problema será resuelto.

¡Salud!.
  • righteous_trespasser
  • Scuffle
  • Genius
  • Avatar de Usuario
  • Registrado: Mar 12, 2007
  • Mensajes: 6228
  • Loc: South-Africa
  • Status: Offline

Nota Mayo 24th, 2009, 11:27 pm

Hola, sólo tiene que ir a la Yahoo Weather Página de inicio y en esa lista, se encuentran la región que está buscando y podrá ver en la url que las regiones es un código único que sólo tienes que entrar en la solicitud de URL...Así que digamos estoy buscando en todas las regiones del Sur-África que se destinarán a esto página y mire el código de cada región como flotar por el enlace...malos y, a continuación, crear una página que tenga ese código dinámica y envía una solicitud de URL y, a continuación, muestra los datos pertinentes.
Let's leave all our *plum* where it is and go live in the jungle ...
  • thunderball
  • Born
  • Born
  • No Avatar
  • Registrado: Oct 07, 2009
  • Mensajes: 2
  • Status: Offline

Nota Octubre 7th, 2009, 1:40 pm

Gracias por el tutorial, yo estaba buscando por todas partes para ello.

Pegué el código directamente desde el archivo descargado y tiene este error:

Código: [ Select ]
Parse error: syntax error, unexpected T_OBJECT_OPERATOR on line 17

line 17 is "$description = $describe->item(0)->nodeValue;"
  1. Parse error: syntax error, unexpected T_OBJECT_OPERATOR on line 17
  2. line 17 is "$description = $describe->item(0)->nodeValue;"


alguna sugerencia?

Thx
  • Anonymous
  • Bot
  • No Avatar
  • Registrado: 25 Feb 2008
  • Mensajes: ?
  • Loc: Ozzuland
  • Status: Online

Nota Octubre 7th, 2009, 1:40 pm

Publicar Información

  • Total de mensajes en este tema: 22 mensajes
  • Moderador: Tutorial Writers
  • Usuarios navegando por este Foro: No hay usuarios registrados visitando el Foro y 1 invitado
  • No puede abrir nuevos temas en este Foro
  • No puede responder a temas en este Foro
  • No puede editar sus mensajes en este Foro
  • No puede borrar sus mensajes en este Foro
  • No puede enviar adjuntos en este Foro
 
 

© 2011 Unmelted, LLC. Ozzu® es una marca registrada de Unmelted, LLC