从字符串结果cURL调用到使用PHP的数组

时间:2016-03-06 22:26:43

标签: php arrays json curl wampserver

我通过我的localhost Wampserver从Paypal移动SDK获得回复。我通过cURL调用收到一个字符串。此字符串已通过在线服务Json Lint网站验证为json形式。我能够将json字符串转换为php代码中的数组,使用在线php编译器,phptester.net使用php 5.5版。但是,当我在我的wampserver上尝试相同的代码时,它表示数组大小等于零。我不知道会出现什么问题。请帮我评估我的PHP代码。

以下是Paypal mobile sdk的回复:

{"scope":"https://uri.paypal.com/services/subscriptions https://api.paypal.com/v1/payments/.* https://api.paypal.com/v1/vault/credit-card https://uri.paypal.com/services/applications/webhooks openid https://uri.paypal.com/payments/payouts https://api.paypal.com/v1/vault/credit-card/.*","nonce":"2016-03-06T22:13:44ZNxK118Mc40QthTeJX8Y_enneSe0y62kEo6mu0ICCwMU","access_token":"A101.ONfkNw-H4-VcjWL9ZUbLlaDj1YUApO7X9fhOslMKRLyW1JpKL1hLlD5W2m9xri-y.ZRF-23gpYMDQ5vWPkOsEiv8WbJC","token_type":"Bearer","app_id":"APP-80W284485P519543T","expires_in":32399}

这是我在php文件中使用的相关代码:

  curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
    curl_setopt($ch,CURLOPT_HEADER,true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header_array);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string); 
    curl_setopt($ch, CURLOPT_USERPWD, $idclient.":".$sekret);  


    $result = curl_exec($ch);
    echo curl_error($ch);
    curl_close($ch);

    echo $result;
    $arr = (array) json_decode($result);
    $token = $arr['access_token'];

    echo "here's the token oken";
    var_dump($arr);
    var_dump($token);

这是我在phptester.net中使用的代码:

$e ='I copied and paste the response i get from server here. noticed the
single quotes here. Maybe this is the problem';
$a = (array)json_decode($e);
$b = $a['access_token'];
var_dump($b);    

此代码准确地在“access_token”处打印出数组的值,这是我需要验证对PayPal付款的access_token。

我需要在我的Wamp服务器php文件上复制这个好的代码。但它没有做到应该做的事情。它表示我的数组的大小为零,并且变量$ token为null。请帮我评估我的代码。

谢谢

1 个答案:

答案 0 :(得分:0)

试试这个,不要试图将json_decode强制转换为数组。您可以使用json_decode中的第二个选项将其转换为关联数组。 PHP Doc

$e ='{"scope":"https://uri.paypal.com/services/subscriptions https://api.paypal.com/v1/payments/.* https://api.paypal.com/v1/vault/credit-card https://uri.paypal.com/services/applications/webhooks openid https://uri.paypal.com/payments/payouts https://api.paypal.com/v1/vault/credit-card/.*","nonce":"2016-03-06T22:13:44ZNxK118Mc40QthTeJX8Y_enneSe0y62kEo6mu0ICCwMU","access_token":"A101.ONfkNw-H4-VcjWL9ZUbLlaDj1YUApO7X9fhOslMKRLyW1JpKL1hLlD5W2m9xri-y.ZRF-23gpYMDQ5vWPkOsEiv8WbJC","token_type":"Bearer","app_id":"APP-80W284485P519543T","expires_in":32399}';

$a = json_decode($e,true);

$b = $a['access_token'];

var_dump($b);

这里