我的PHP中出现“意外的T_STRING”错误?

时间:2012-02-03 19:18:13

标签: php

我遇到了一些我正在尝试使用的PHP代码的问题。我一直收到“意外的T_STRING”错误?这是我的测试页面上的代码:

   <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
   <html xmlns="http://www.w3.org/1999/xhtml">

    <?php
    include 'http://www.weather.gov/xml/current_obs/KTPA.xml';

    $current_observation = new SimpleXMLElement($xmlstr);

    echo $current_observation->location[0]->plot;
    echo $current_observation->weather[0]->plot;
    echo $current_observation->temperature_string[0]->plot;
    echo $current_observation->wind_string[0]->plot;

    ?>

我想要做的是从此国家气象服务XML文件中提取天气数据,并以类似于NWS在该页面上执行此操作的方式显示它。但是,上面的代码返回此消息:“解析错误:语法错误,第1行http://www.weather.gov/xml/current_obs/KTPA.xml中的意外T_STRING”。这是我能解决的问题吗?我是PHP的新手,所以您可以提供任何帮助。

5 个答案:

答案 0 :(得分:5)

include函数用于包含其他php脚本。要获取xml文件的内容,您必须使用file_get_contents

$xmlstr =  file_get_contents('http://www.weather.gov/xml/current_obs/KTPA.xml');

$current_observation = new SimpleXMLElement($xmlstr);

echo $current_observation->location[0]->plot;
echo $current_observation->weather[0]->plot;
echo $current_observation->temperature_string[0]->plot;
echo $current_observation->wind_string[0]->plot;

答案 1 :(得分:2)

不确定您是否理解include的目的。要获取文件的内容,请使用file_get_contents。就这样:

$xmlstr = file_gets_contents('http://www.weather.gov/xml/current_obs/KTPA.xml');

答案 2 :(得分:1)

当您在PHP源代码中包含任何非法引用的文本字符串时,您将收到T_STRING错误。

可能的原因:

您不能在PHP源文件中“包含”非PHP文本。

解决方案:

使用PHP“fopen()”(或等效的)来阅读和解析您感兴趣的文件。

更好的是,如果文件是XML,那么使用PHP XML来解析它:

答案 3 :(得分:1)

首先,这个脚本应该在html和doctype标签之前运行,你没有用头部和主体完成你的html代码那些应该始终是你的html网页的基础。

其次,$ xmlstr指向的地方,你从未创建过变量$ xmlstr,而你包含的网页是xml,所以也不会这样做。 如果您使用自己的设置Web服务器,则可以启用cUrl,您可以在其中解析xml源代码,将其保存到变量中并使用数组和for循环逐步显示它。 您可以将解析后的数据保存在如下数组中:

使用cUrl你得到一个输出,你可以保存在一个变量中,让我们说$ output。 从那里开始,你将不得不一步一步地解析你的解析方式,所以首先你要做echo $ output;因此,当您使用cUrl时,您知道源实际上是什么样子,下一步是找到该URL中的特定数据并使用explode(创建数组)和子字符串解析到这一点,您可以将它们保存到数组中,如: $ city [$ cityName] [$ temp]或类似的东西

答案 4 :(得分:0)

我会尝试为你要解析的变量分配一些东西,因为只是包含文件不会起作用,因为它不是一个可以解释并包含在输出中的PHP脚本。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
   <html xmlns="http://www.w3.org/1999/xhtml">

    <?php
    $xmlstr = simplexml_load_file('http://www.weather.gov/xml/current_obs/KTPA.xml');
    $current_observation = new SimpleXMLElement($xmlstr);

    echo $current_observation->location[0]->plot;
    echo $current_observation->weather[0]->plot;
    echo $current_observation->temperature_string[0]->plot;
    echo $current_observation->wind_string[0]->plot;

    ?>