【问题标题】:Extracting Content-Type of external website and save the value on JSON file as "Null"提取外部网站的 Content-Type 并将 JSON 文件中的值保存为“Null”
【发布时间】:2018-06-07 12:43:26
【问题描述】:

我正在尝试提取外部网站的编码并将其保存在 JSON 文件 (UTF-8) 中。

在我尝试“www.secra.de”之前它运行良好,它将此页面中的值保存为 Null。

正如我所见,在“Content-Type”上获得的值超过了值,我认为这可能是重定向,但我不确定。

最好的解决方法是什么?

    $domain   = "http://www.secra.de";
    $info = get_headers($domain, 1)["Content-Type"];
    $infostr = explode('=', $info);
    $encoding = end($infostr);

    if (!empty($info)){
        $data_array[$key]['encode'] = $encoding;
    } else {
        $data_array[$key]['encode'] = "It don't have Encode";
    }
    $json = json_encode($data_array);
    file_put_contents('data/data.json', $json);
};

【问题讨论】:

  • $info 的值到底是什么不起作用...?
  • $info 正在工作,我做了一些“测试”,问题是 $infostr = explode('=', $info);我认为,如果我打印 $info,它会显示所有 Content-Type 的值,但如果我打印 $encoding,它会显示“Null”
  • 那么,我再说一遍,$info 不起作用时的具体值是多少?如果您将$info 替换为'text/html; charset=utf-8',那么您的代码可以正常工作。
  • 是值:text/html;字符集=iso-8859-1 [1] => 文本/html; charset=utf-8
  • 什么?你到底是从哪里得到这个值的?

标签: php json null


【解决方案1】:

问题在于http://www.secra.de 重定向到https://www.secra.de,而get_headers 函数为您返回两个原始请求和重定向请求的Content-Type:

[Content-Type] => Array
    (
        [0] => text/html; charset=iso-8859-1
        [1] => text/html; charset=utf-8
    )

所以问题是当$info 是一个数组时,您将它视为一个字符串。修复:

$info = get_headers($domain, 1)["Content-Type"];
if (is_array($info)) {
    $info = end($info);
}
$infostr = explode('=', $info);
$encoding = end($infostr);

【讨论】:

  • 一个问题,你能解释一下你的这行代码吗? if (is_array($info)) { $info = end($info); }
猜你喜欢
  • 2021-10-15
  • 2023-03-26
  • 2018-05-22
  • 2012-05-22
  • 2020-01-22
  • 1970-01-01
  • 1970-01-01
  • 2014-09-21
  • 2010-09-18
相关资源
最近更新 更多