Youtube API插入commentThread PHP

时间:2015-10-08 11:38:54

标签: php youtube-api

此代码不起作用,我无法解决。

$data_channel = '{
    "snippet":
    {
        "topLevelComment":
        {
            "snippet":
            {
                "videoId":"'.$_POST['id_video'].'"
                "textOriginal":"'.$_POST['comment'].'"
            }
        }
    }
}';

echo $_COOKIE['access_token'];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://www.googleapis.com/youtube/v3/commentThreads?part=snippet&access_token='.$_COOKIE['access_token']);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_channel);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
    'Content-Type: application/json')                                                                      
);        

$req_comment = curl_exec($ch);
curl_close($ch);

错误消息 代码: '400' 消息:'解析错误'

授权使用范围force.ssl

完成
{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "parseError",
    "message": "Parse Error"
   }
  ],
  "code": 400,
  "message": "Parse Error"
 }
}

返回请求正文错误

1 个答案:

答案 0 :(得分:0)

这很可能会产生JSON错误:

...
                "textOriginal":"'.$_POST['comment'].'"
            }
        }
    }
}';

更好的是:

data_channel = array(
    "snippet" => array(
            "topLevelComment" => array(
                  "snippet" => array (
                      "videoId" => $_POST['id_video'],
                      "textOriginal" => $_POST['comment']
                  )
             )
    )
);
$data_json = json_encode($data_channel, JSON_HEX_QUOT + JSON_HEX_TAG + JSON_HEX_AMP + JSON_HEX_APOS + JSON_FORCE_OBJECT);

并进一步

curl_setopt($ch, CURLOPT_POSTFIELDS, $data_json);

因为文本可能包含(...包含)json的无效字符。 json_encode处理aht并正确编码