如何查看,网页有效?

时间:2013-08-16 14:09:16

标签: php parsing

我的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来源:
$消息= ABC;

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

如果$ message = london;

  <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>

2 个答案:

答案 0 :(得分: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
}

答案 1 :(得分: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.";