3

次のように simpleXML url をロードしています。

$City_and_State = "Miami,FL"

    $url="https://www.google.com/ig/api?weather=$City_and_State&hl=en&referrer=googlecalendar";
    $xml = simplexml_load_file($url);

返されるデータは次のとおりです。

<?xml version="1.0"?>
<xml_api_reply version="1">
  <weather section="0" row="0" mobile_zipped="1" mobile_row="0" tab_id="0" module_id="0">
    <forecast_information>
      <city data="Miami, FL"/>
      <postal_code data="Miami,FL"/>
      <latitude_e6 data=""/><longitude_e6 data=""/>
      <forecast_date data="2013-08-26"/>
      <current_date_time data="1970-01-01 00:00:00 +0000"/>
      <unit_system data="US"/>
    </forecast_information>
    <current_conditions>
      <condition data="Mostly Cloudy"/>
      <temp_f data="86"/><temp_c data="30"/>
      <humidity data="Humidity: 76%"/>
      <icon data="/ig/images/weather/mostly_cloudy.gif"/>
      <wind_condition data="Wind: NE at 0 mph"/>
    </current_conditions>
    <forecast_conditions>
      <day_of_week data="Mon"/>
      <low data="77"/>
      <high data="93"/>
      <icon data="/ig/images/weather/thunderstorm.gif"/>
      <condition data="Thunderstorm"/>
    </forecast_conditions>
    <forecast_conditions>
      <day_of_week data="Tue"/>
      <low data="77"/>
      <high data="93"/>
      <icon data="/ig/images/weather/chance_of_storm.gif"/>
      <condition data="Chance of Storm"/>
    </forecast_conditions>
    <forecast_conditions>
      <day_of_week data="Wed"/>
      <low data="77"/>
      <high data="93"/>
      <icon data="/ig/images/weather/chance_of_storm.gif"/>
      <condition data="Chance of Storm"/>
    </forecast_conditions>
    <forecast_conditions>
      <day_of_week data="Thu"/>
      <low data="79"/>
      <high data="93"/>
      <icon data="/ig/images/weather/chance_of_storm.gif"/>
      <condition data="Chance of Storm"/>
    </forecast_conditions>
  </weather>
</xml_api_reply>

今なら$City_and_State = "Bablablablalba"

次に、これが私が得るものです:

<?xml version="1.0"?>
<xml_api_reply version="1">
  <weather section="0" row="0" mobile_zipped="1" mobile_row="0" tab_id="0" module_id="0">
    <problem_cause data=""/>
  </weather>
</xml_api_reply>

したがって、最初のものには天気データがあり、2 番目のものにはありません。

気象データが存在するかどうかを確認するにはどうすればよいですか? (要素が存在するか、子か、このようなものがあるかどうかを確認してください。)

以下を試しましたが、うまくいきません。

if( $xml->weather->current_conditions->condition->attributes()->data  != '' ) {
 echo 'Weather Data Exists';
 } else {
 echo 'Weather Data Does NOT Exists';
 }
4

1 に答える 1

7

の存在を探すだけです$xml->weather->problem_cause。これは、悪い XML にのみ表示されるようです。

if (isset($xml->weather->problem_cause)) {
    // you have a problem
} else {
    // you received data
}

$xml->weather->forecast_informationまたは、データが存在するという肯定的なアサーションとしての存在を探すこともできます。

于 2013-08-26T17:48:53.680 に答える