PHP CURL Using POST Raw JSON Data

前端 未结 2 1715
终归单人心
终归单人心 2020-12-18 00:37

I am working with PHP curl for post, for some reason I couldn\'t post the form successfully.

$ch = curl_init();
$headers = [
            \'x-api-key: XXXXXX         


        
相关标签:
2条回答
  • 2020-12-18 01:18

    If you want an arranged and explained format, see the code below.

    // Set The API URL
    $url = 'http://www.example.com/api';
    
    // Create a new cURL resource
    $ch = curl_init($url);
    
    // Setup request to send json via POST`
    $payload = json_encode(array(
        'data1' => 'value1',
        'data2' => 'value2'
       )
    );
    
    // Attach encoded JSON string to the POST fields
    curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
    
    // Set the content type to application/json
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('x-api-key: XXXXXX', 'Content-Type: text/plain'));
    
    // Return response instead of outputting
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    
    // Execute the POST request
    $result = curl_exec($ch);
    
    // Get the POST request header status
    $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    
    // If header status is not Created or not OK, return error message
    if ( $status !== 201 || $status !== 200 ) {
       die("Error: call to URL $url failed with status $status, response $result, curl_error " . curl_error($ch) . ", curl_errno " . curl_errno($ch));
    }
    
    // Close cURL resource
    curl_close($ch);
    
    // if you need to process the response from the API further
    $response = json_decode($result, true);
    

    I hope this helps someone

    0 讨论(0)
  • 2020-12-18 01:22

    If you wanna use Content-type: application/json and raw data, seem your data should be in json format

    $ch = curl_init();
    $headers  = [
                'x-api-key: XXXXXX',
                'Content-Type: text/plain'
            ];
    $postData = [
        'data1' => 'value1',
        'data2' => 'value2'
    ];
    curl_setopt($ch, CURLOPT_URL,"XXXXXX");
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));           
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    $result     = curl_exec ($ch);
    $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    
    0 讨论(0)
提交回复
热议问题