Treeves
Treeves

Reputation: 23

JSON/CURL issue

My CURL request takes in two variables as shown below:

<?php
$id             =       $_GET["id"];
$review         =       $_GET["review"];
$url = 'http://edward/~treeves/ratingJSON.php';

$jsonData = array("id" => "$id", "review" => "$review");

$ch = curl_init($url);

$jsonDataEncoded = json_encode($jsonData);

curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, array('json' => $jsonDataEncoded));
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); 

$result = curl_exec($ch);
?>

And posts it to the web service shown below:

<?php
header("Content-type: application/json");


    try {
        $conn           =       new PDO("mysql:host=localhost;dbname=treeves;", "treeves", "oopheiye");
        $json           =       $_POST["json"];
        $data           =       json_decode ($json, true);      
        $result         =       $conn->query("INSERT INTO poi_reviews (poi_id, review) 
                                              VALUES ('$data[ID]', '$data[review]')");

        } catch (Exception $e) {
        echo $e->getMessage();
    }
?>

However the data being inserted is blank. When I use var_dump($data) on the web service is shows 1 NULL. I think it's to do with the variables in the CURL file as the web service works. Any ideas?

Update Taking out the HTTP header and using 'var_dump($data, $error === JSON_ERROR_UTF8)' is returning the following:

array(2) { ["id"]=> string(4) "1014" ["review"]=> string(1) "2" } bool(false)

Upvotes: 2

Views: 99

Answers (1)

Quentin
Quentin

Reputation: 943220

Here you set up form encoded data with one key (json) that has a value (of JSON encoded data):

curl_setopt($ch, CURLOPT_POSTFIELDS, array('json' => $jsonDataEncoded));

Here you tell the server that you are sending JSON and not form encoded data.

curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); 

One of the above has to be wrong, since they are contradictory.


Here you try to read form encoded data:

$_POST["json"];

So claiming you are sending plain JSON is wrong (your JSON is encapsulated in form encoding).

Remove this line:

curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); 

Upvotes: 1

Related Questions