json_decode 返回空值而不是数组

json_decode is returning a null value instead of an array

我正在尝试在解码数据中搜索关键字电子邮件。但是它无法从 json_decode.

获取数组类型

这是代码

$curl = curl_init();

curl_setopt_array($curl, array(
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_URL => $url,
    CURLOPT_USERAGENT => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.81 Safari/537.36'
));

$resp = json_decode(curl_exec($curl), true);


if(is_array($resp) && array_key_exists("email", $resp))
{
  echo $data_arr[0] . "email: ";
  $content = $resp["email"];
  fwrite($fp,$content);
}

准确的错误是:

array_key_exists() expects parameter 2 to be array, null given in index.php on line 34

编辑:我稍微发现了错误。由于错误(url 格式错误),Curl 执行失败。仍然无法弄清楚 url 在这种情况下是如何畸形的。 url 是这样提取的。

$data = fgets($fp);
$data_arr = split(",", $data);
$token_arr = isset($data_arr[1]) ? split('"', $data_arr[1]) : null;

$url = isset($token_arr[1]) ? "https://graph.facebook.com/v2.3/me?access_token=" . $token_arr[1] : null;

尝试使用 utf8_encode

$data = curl_exec($curl);
$data = utf8_encode($data);
$resp = json_decode($data, true);

Note: utf8_decode work only with utf8

This function only works with UTF-8 encoded strings.

PHP implements a superset of JSON as specified in the original » RFC 4627 - it will also encode and decode scalar types and NULL. RFC 4627 only supports these values when they are nested inside an array or an object. Although this superset is consistent with the expanded definition of "JSON text" in the newer » RFC 7159 (which aims to supersede RFC 4627) and » ECMA-404, this may cause interoperability issues with older JSON parsers that adhere strictly to RFC 4627 when encoding a single scalar value.

Source: http://php.net/manual/en/function.json-decode.php

需要在 URL 中编码参数,请尝试 urlencoderawurlecnode,示例:

Note, I added () in ? :

$data = fgets($fp);
$data_arr = split(",", $data);
$token_arr = isset($data_arr[1]) ? split('"', $data_arr[1]) : null;

$url = isset($token_arr[1]) ? ("https://graph.facebook.com/v2.3/me?access_token=" . urlencode($token_arr[1])) : null;

检查是否发送NULL

如果 curl_error return malformed 意思是 $url = NULL,问题出在你生成令牌的代码中,试试这个:

$data = fgets($fp);
$data_arr = split(",", $data);
$token_arr = isset($data_arr[1]) ? split('"', $data_arr[1]) : null;

$url = isset($token_arr[1]) ? ("https://graph.facebook.com/v2.3/me?access_token=" . $token_arr[1]) : null;

if (empty($url)) {
   echo 'URL is NULL or EMPTY';
   exit;
}

$curl = curl_init();

curl_setopt_array($curl, array(
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_URL => $url,
    CURLOPT_USERAGENT => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.81 Safari/537.36'
));

$data = curl_exec($curl);
$data = utf8_encode($data);
$resp = json_decode($data, true);

if(is_array($resp) && array_key_exists("email", $resp))
{
  echo $data_arr[0] . "email: ";
  $content = $resp["email"];
  fwrite($fp,$content);
}