简体   繁体   中英

How do I access this JSON Element? (PHP)

What am I doing wrong? This is my code:

$json_url = ";
$apikey = "..........";

$data_json = '{"user":"...........",
"customer" {"username":".....","password":".....","phishing":"....."},"seller":{"username":".....","password":"......","phishing":"....."},"amount":10000,"platform":"ps"}';


    $ch = curl_init($json_url);

    curl_setopt_array($ch, array(
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => $data_json,
    CURLOPT_HEADER => true,
    CURLOPT_HTTPHEADER => array(
              'Connection: keep-alive',
              'Accept: application/json',
              'Content-Type: application/json; charset=utf-8',
              'Host: futservices.com',
              'Content-Length: '.strlen($data_json).'',
              'Accept-Encoding: gzip'
              ))
   );

    
    $response  = curl_exec($ch);
    curl_close($ch);

    echo $response;

    $order = json_decode($response, true);

    
    echo "Your Token Is: ".$order['d'];`

The request goes through fine, however, I want to grab the "d" JSON element that sent by in a JSON Response from the API.

This is the response:

HTTP/1.1 200 OK Cache-Control: private, max-age=0 Content-Length: 44 Content-Type: application/json; charset=utf-8 Server: Microsoft-IIS/8.5 X-AspNet-Version: 4.0.30319 X-Powered-By: ASP.NET Date: Sat, 25 Apr 2015 16:58:09 GMT {"d":"d922bad4-60d8-4fe4-9cba-0231328744a0"}1Your Token Is:

As you can see "d" is not echoed after "Your Token Is: ". How can I resolve this?

You need to set the CURLOPT_RETURN_TRANSFER flag to store the result of a CURL as a variable. What's happening is that the response is just being sent straight to your browser. Add the option as I have done below.

 curl_setopt_array($ch, array(
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => $data_json,
    CURLOPT_HEADER => true,
    CURLOPT_RETURN_TRANSFER => true,
    CURLOPT_HTTPHEADER => array(
              'Connection: keep-alive',
              'Accept: application/json',
              'Content-Type: application/json; charset=utf-8',
              'Host: futservices.com',
              'Content-Length: '.strlen($data_json).'',
              'Accept-Encoding: gzip'
              ))
   );

I hope that helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM