PHP file_get_contents 在应该返回错误时却没有返回错误

问题描述 投票:0回答:3

我正在使用 file_get_contents 从 URL 获取 json。同一个 URL 有时有效,有时无效。如果没有,file_get_contents 不会返回任何错误,只是停止整个脚本。太混乱了。

php file-get-contents
3个回答
0
投票

您收到什么错误?这是警告还是致命错误?

如果是警告,请在 file_get_contents 前添加@,例如:@file_get_contents 如果其他,请在执行其他过程之前检查数据

$jsondata =@file_get_contents('YOur URl');
if($jsondata){
  // Process your code
}else{
  //do nothing
}

0
投票

未输出正确数据时返回的 URL 是什么?

1)

 $json_data =file_get_contents('URl');
    if($json_data){
       //parse the data
      }else{
        //show error
     }

2 查找 url 到底返回的内容

$json_data =file_get_contents('URl');
var_dump($json_data);

3使用cURL

$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, 'url_here');
$result = curl_exec($ch);
curl_close($ch);
$obj = json_decode($result);
var_dump($obj)

0
投票

我也有同样的问题。 事实证明,当我打印出 HTML 数据时,我可以检索到数据。但我的 PHP 脚本在那之后立即停止,没有错误消息。

我意识到: 为了检查检索到的数据的大小,我使用了

$size = str_len($page)

而不是

strlen($page)

但脚本就停在这一行后面。

原因是,我曾经在整个响应中搜索子字符串

if(str_contains($page, 'Neelde'))

但是这个功能是在 php 8 中引入的,而我的服务器使用的是 php v7.6。

所以我添加了

if (!function_exists('str_contains')) {
    function str_contains( $haystack, $needle)
    {
        return $needle !== '' && mb_strpos($haystack, $needle) !== false;
    }
}

我的脚本运行正确。

因此检查 file_get_contents(...

后面是否有任何语法错误
© www.soinside.com 2019 - 2024. All rights reserved.