Home » Php » Print Specific data from JSON in php

Print Specific data from JSON in php

Posted by: admin February 25, 2020 Leave a comment

Questions:

Hello I am fairly new to json and cURL in the wordpress enviroment. I am trying to clean up the json data that is outputted from my cURL response. Right now it starts off like this

{"resultCode":"SUCCESS",
"resultReason":null,
"resultDetail":null,
"data":{"page_count":50,
        "total_count":1948,
        "product_list":[{"product_id":"014a20b1-dbe7-11e8-a53e-0236cac9056a",
                        "product_status":"ACTIVE",
                        "last_updated_at":"2019-10-07T15:43:54.000-...

I would like it to start here when it gets printed after “data”:

{"page_count":50,
 "total_count":1948,
 "product_list":[{"product_id":"014a20b1-dbe7-11e8-a53e-0236cac9056a",
                  "product_status":"ACTIVE",
                  "last_updated_at":"2019-10-07T15:43:54.000-...

the php function i have it under looks like this:

function cornerstonetreez () {

    $ch = curl_init();
    curl_setopt($ch, 
    CURLOPT_URL,"https://api.treez.io/v2.0/dispensary/cornerstone/product/product_list? 
    category_type=all&page=1&pagesize=50&active=true");

    $headers = array();
    $headers[] = 'authorization: authorizationkeyhere';
    $headers[] = 'client_id: clientkey';
    curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
    $server_output = curl_exec ($ch);

    curl_close ($ch);
    $json_string = json_encode($server_output, JSON_PRETTY_PRINT);
    print  $json_string ;
}
add_shortcode( 'helloworld', 'cornerstonetreez' );

any help would be greatly appreciated. Thank you!

How to&Answers:

Does this work?

<?php function cornerstonetreez () {

$ch = curl_init();
curl_setopt($ch, 
CURLOPT_URL,"https://api.treez.io/v2.0/dispensary/cornerstone/product/product_list? 
category_type=all&page=1&pagesize=50&active=true");

$headers = array();
$headers[] = 'authorization: authorizationkeyhere';
$headers[] = 'client_id: clientkey';
curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

$server_output = json_decode(curl_exec ($ch));

curl_close ($ch);
$json_string = json_encode($server_output->data, JSON_PRETTY_PRINT);
print  $json_string ;
}
add_shortcode( 'helloworld', 'cornerstonetreez' );

Edit:

the code was missing CURLOPT_RETURNTRANSFER which caused the code to print twice, plus it had to use json_decode and then encode again but with data only

Answer:

First you need to convert the JSONString into a PHP object or array. Then you can address the section you want to i.e. $obj->data

Then you will likely need to convert it to another JSON String to pass it on to whereever it is being print’ed to

$server_output = curl_exec ($ch);

$obj = json_decode($server_output);
print json_encode($obj->data);