PHP发布请求(CURL,JSON)不起作用

时间:2020-04-29 23:17:35

标签: php json api curl

在我的这个问题上,我谦虚地向伟大的开发者致意。将JSON格式的发布请求发送到Firebase。这是我的代码

addEventListener()

但是我收到一个错误:

“详细信息”:[{“消息”:“ \” id \”是必需的”,“路径”:[“ id”],“类型”:“任何必填”,“上下文”:{“标签“:” id“,” key“:” id“}}]}

2 个答案:

答案 0 :(得分:2)

请尝试这样发送:

    $params = $myDataArray;
    $data_string = json_encode($params);
    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_URL => $toEndPoint,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS => $data_string,
        CURLOPT_HTTPHEADER => array(
            "x-access-token: $token",
            "cache-control: no-cache",
            "content-type: application/json",
        ),
    ));

    $response = curl_exec($curl);
    $err = curl_error($curl);
    curl_close($curl);
    if ($err) {
        echo "cURL Error #:" . $err;
    } else {
        echo $response;
    }
    exit;

答案 1 :(得分:0)

@godlovesme,回答您的最新评论:

我真的不喜欢使用While循环,因为它们很容易让您陷入无休止的循环,但是您可以满足您的要求:

$i = 0;
$questionsArrFormatted = [];
while ($i < count($questionsArr)) {
    $hasImage = count($questionsArr[$i]['question']) ? true : false;
    $questionsArrFormatted[$i] = [
        'question' => $questionsArr[$i]['question'],
        'questionMark' => $questionsArr[$i]['marks'],
        'options' => $questionsArr[$i]['options'], // options should be an array formatted like in your question
        'hasImage' => $hasImage,
        'images' => $questionsArr[$i]['images'],
        'correctionOption' => $questionsArr[$i]['correct_answer']
    ];
    $i++;
}

$data = array(
    'id' => 156,
    'quizName' => $quizName,
    'numberOfQuestions' => $numberOfQuestions,
    'isTimed' => true,
    'numberOfMinutesToComplete' => $numberOfMinutesToComplete,
    'targetedClass' => 'Js One',
    'subject' => $subject_name,
    'schoolLevel' => $schoolLevel,
    'questions' => $questionsArrFormatted,
    'totalValidMarks' => $totalValidMarks,
    'validUntil' => $validUntil
);