0

我的 PHP 代码:

include 'simple_html_dom.php';

$value1 = "http://isitraining.in/$message";
$html = file_get_html($value1);

$rain = $html->find('h1');
$weather = $html->find('h2');
$rains = strip_tags($rain[0]);
weathers = strip_tags($weather[0]);

它适用于有效的城市名称 $message=london;

如果不是有效的城市名称,如果 $message=abc;
它像这样返回:

Fatal error: Call to a member function find() on a non-object

我的 HTML 源代码:
$message=abc;

  <h1>Oops!</h1>
  <h2>No results! There might be something wrong with the city name..</h2>

如果$消息=伦敦;

  <h1>No</h1>
  <h2>Conditions for <strong>London, England, United Kingdom</strong><br/>on Fri, 16 Aug 2013 2:18 pm BST: <strong>Mostly Cloudy</strong> (22&deg;C, 70&deg;F)</h2>
4

2 回答 2

0

原因不是因为您将变量设置为 abc,而是因为 URL 不存在。当您要求检查网页是否有效时,我假设这就是您的意思。您可以尝试获取页面的标题,如果它们返回 404,那么您可能会抛出错误:

include 'simple_html_dom.php';

$value1 = "http://isitraining.in/$message";
$file_headers = @get_headers($value1);

if($file_headers[0] == 'HTTP/1.1 404 Not Found') {
    echo "File was not found!";
} else {
    $html = file_get_html($value1);

    $rain = $html->find('h1');
    $weather = $html->find('h2');
    $rains = strip_tags($rain[0]);
    weathers = strip_tags($weather[0]);

    // Rest of your code goes here
}
于 2013-08-16T14:15:20.577 回答
0

您还可以检查是否$html是一个对象:

include 'simple_html_dom.php';

$value1 = "http://isitraining.in/$message";
$html = file_get_html($value1);

if (is_object($html))
{
    $rain = $html->find('h1');
    $weather = $html->find('h2');
    $rains = strip_tags($rain[0]);
    $weathers = strip_tags($weather[0]);
}
else
    echo "No good.";
于 2013-08-16T14:20:13.263 回答