Incorrect response json coding and array violation Woocomerce 3

I get the answer in the wrong encoding. Perhaps because of this, the array construction does not work. How to fix it?

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://app.example.com/api/index.php?get_status");
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$result = curl_exec($ch);
curl_close($ch);

$decoded = (array) json_decode($result);

// Update order status
if( isset($decoded['result']) && $decoded['result'] == 'success' && isset($decoded['status']) && ! empty($decoded['status']) ){
    if( $decoded['status'] == "Order Completed" )
        $order->update_status( 'completed' );
    elseif( $decoded['status'] == "Order Cancelled" )
        $order->update_status( 'cancelled' );
}

I looked for solutions and tried it, but it does not work either:

$decoded = (array) json_decode($result, JSON_UNESCAPED_UNICODE);

print_r( $decoded ); show:

Array ( ) Array ( ) Array ( ) Array ( ) Array ( ) Array ( ) Array ( ) Array ( ) Array ( ) Array ( ) Array ( ) Array ( ) Array ( ) Array ( ) Array ( ) Array ( ) Array ( ) Array ( ) Array ( ) Array ( ) Array ( ) Array ( ) Array ( ) Array ( ) Array ( ) Array ( ) Array ( ) Array ( ) Array ( ) Array ( ) Array ( ) Array ( ) Array ( ) Array ( ) Array ( ) Array ( )

print_r ( $result ); show:

HTTP/1.1 200 OK Server: nginx/1.2.1 Date: Thu, 05 Jul 2018 18:59:07 GMT Content-Type: text/html; charset=windows-1251 Transfer-Encoding: chunked Connection: keep-alive X-Powered-By: PHP/5.4.45-0+deb7u2 Vary: Accept-Encoding Strict-Transport-Security: max-age=31536000; {"result":"success","status":"\u0412\u044b\u043f\u043e\u043b\u043d\u0435\u043d"}

Upvotes: 1

Views: 39

Answers (1)

lovelace
lovelace

Reputation: 1205

You are asking to receive header info in the server response. You can't decode this with json_decode().

To get a pure JSON-only response from the server, you need to set:

curl_setopt($ch, CURLOPT_HEADER, false);

Once you get the valid JSON in your response, you can turn it into a PHP array as follows(set the second arg to true): $decoded = json_decode($result, true);

Now $decoded is a PHP associative array that you can traverse.

Upvotes: 1

Related Questions