JSON decoding after submit using PHP cUrl

I researched everywhere and can't figure it out.

I am writing a cUrl test request to test my REST service:

// initialize curl handler
$ch = curl_init();

$data = array(
"products" => array ("product1"=>"abc","product2"=>"pass"));
$data = json_encode($data);

$postArgs = 'order=new&data=' . $data;

// set curl options
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLINFO_HEADER_OUT, TRUE);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postArgs);
curl_setopt($ch, CURLOPT_URL, 'http://localhost/store/rest.php');

// execute curl
curl_exec($ch);

This works fine, and the request is accepted by my service, and $ _Post is populated as necessary with two variables, order and data. Data has an encoded JSON object. And when I print $ _Post ['data'], it shows:

{"products":{"product1":"abc","product2":"pass"}}

This is exactly what is expected and identical to what was sent.

When I try to decode this, json_decode () returns nothing!

If I create a new line and manually type this line, json_decode () works fine!

I tried:

strip_tags(), , http utf8_encode() utf 8 addslashes(),

.

, json_decode() , http-?

:

public static function processRequest($requestArrays) {
    // get our verb
    $request_method = strtolower($requestArrays->server['REQUEST_METHOD']);
    $return_obj = new RestRequest();
    // we'll store our data here
    $data = array();

    switch ($request_method) {
        case 'post':
            $data = $requestArrays->post;
            break;
    }

    // store the method
    $return_obj->setMethod($request_method);

    // set the raw data, so we can access it if needed (there may be
    // other pieces to your requests)
    $return_obj->setRequestVars($data);

    if (isset($data['data'])) {
        // translate the JSON to an Object for use however you want
        //$decoded = json_decode(addslashes(utf8_encode($data['data'])));
        //print_r(addslashes($data['data']));
        //print_r($decoded);
        $return_obj->setData(json_decode($data['data']));
    }
    return $return_obj;
 }
+3
2

, JSON cURL quot; " ". , preg_replace(), , , html_entity_decode() " JSON-.

+2

:

$return_obj->setData(json_decode($data['data']));

$data = json_decode( urldecode( $data['data'] ), true );
$return_obj->setData($data);

, .

0

Source: https://habr.com/ru/post/1780098/


All Articles