【问题标题】:Cannot parse XML from a URL using file_get_contents() in PHP无法在 PHP 中使用 file_get_contents() 从 URL 解析 XML
【发布时间】:2021-08-08 21:00:56
【问题描述】:

我正在尝试使用 PHP 从以下 URL (https://www.aviationweather.gov/adds/dataserver_current/httpparam?dataSource=metars&requestType=retrieve&format=xml&hoursBeforeNow=3&mostRecent=true&stationString=KORL) 提取信息,但由于某种原因,我一直没有收到任何信息。

搜索了一下,终于找到了

<?php
  $url = 'https://www.aviationweather.gov/adds/dataserver_current/httpparam?dataSource=metars&requestType=retrieve&format=xml&hoursBeforeNow=1&stationString=KORL';
  $xml = json_decode(file_get_contents($url));
  echo $xml;
?>

编辑:上面的代码显然是错误的......我更新的(仍然是错误的)代码如下。

  $url = 'https://www.aviationweather.gov/adds/dataserver_current/httpparam?dataSource=metars&requestType=retrieve&format=xml&hoursBeforeNow=3&mostRecent=true&stationString=KORL';
  $xml = simplexml_load_file($url) or die("feed not loading");
 
  $string_data = $xml;
  $xmlstr = simplexml_load_string($string_data);
  $data = (string) $xmlstr->data->METAR->raw_text;
  echo $data;

我需要从中获取的信息是&lt;raw_text&gt;

非常感谢您的帮助!

【问题讨论】:

  • 为什么json_decode() 是一个 XML 文件? file_get_contents($url) 本身是否有效?
  • @brombeer 所以我已经尝试了一切......我提供的示例可能不是最好的,因为它是我最后一次尝试,因为在某些情况下可以将 XML 读取为 JSON .我最近的尝试是:$url = 'https://www.aviationweather.gov/adds/dataserver_current/httpparam?dataSource=metars&amp;requestType=retrieve&amp;format=xml&amp;hoursBeforeNow=3&amp;mostRecent=true&amp;stationString=KORL'; $xml = simplexml_load_file($url) or die("feed not loading"); $string_data = $xml; $xmlstr = simplexml_load_string($string_data); $data = (string) $xmlstr-&gt;data-&gt;METAR-&gt;raw_text; echo $data;
  • 现在您尝试解析它两次。每次你第一次使用一个函数时,你应该花一点时间查看它的手册页并了解它的确切作用。试图从名称中猜测并不总是微不足道的。

标签: php xml api parsing


【解决方案1】:

simplexml_load_file() 时无需simplexml_load_string()。只需像以前一样加载 XML 并访问它:

<?php

$url = 'https://www.aviationweather.gov/adds/dataserver_current/httpparam?dataSource=metars&requestType=retrieve&format=xml&hoursBeforeNow=3&mostRecent=true&stationString=KORL';
$xml = simplexml_load_file($url) or die("feed not loading");

$data = (string) $xml->data->METAR->raw_text;
echo $data;

将输出:

KORL 191653Z 08019G24KT 10SM SCT039 BKN085 29/18 A3018 RMK AO2 RAB17E26 SLP222 P0000 T02890183

【讨论】:

  • 天啊...非常感谢!我很感激你帮助我解决这个问题。也谢谢你的解释!这是一个很大的帮助!
猜你喜欢
  • 2013-05-25
  • 1970-01-01
  • 2021-04-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-07
  • 1970-01-01
相关资源
最近更新 更多