错误的响应json编码和数组违规Woocomerce 3

时间:2018-07-05 21:44:51

标签: php wordpress woocommerce woocommerce-rest-api

我用错误的编码得到答案。也许正因为如此,数组构造无法正常工作。如何解决?

$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' );
}

我正在寻找解决方案并尝试了它,但是它也不起作用:

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

print_r( $decoded );显示:

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 );显示:

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"}

1 个答案:

答案 0 :(得分:1)

您要在服务器响应中接收标头信息。您无法使用json_decode()对此进行解码。

要从服务器获取纯JSON响应,您需要设置:

curl_setopt($ch, CURLOPT_HEADER, false);

一旦您在响应中获得有效的JSON,就可以将其转换为如下所示的PHP数组(将第二个arg设置为true):$decoded = json_decode($result, true);

现在$decoded是一个您可以遍历的PHP关联数组。