I have json result from API like:
{
"pagination":
{
"results" : 2248,
"page" : 1,
"page_size" : 200,
**"pages" : 12**
},
"products" :
[ {"id": "370c3876-a2b9-11e2-b2b4-bc764e10976c", "source_id": "",....}]}
I would like to retrieve "pages" : 12 from pagination. How can I do it?
I tried this and it worked fine
$data = ' {
"pagination":
{
"results" : 2248,
"page" : 1,
"page_size" : 200,
"pages" : 12
}
}';
$response = json_decode($data, true);
echo $response['pagination']['pages'];//12
Use json_decode to decode the api response, then access the property.
Example:
$response = json_decode($data, true);
echo $response['pagination']['pages'];
<?php
$object = json_decode($your_api_return_string);
$pages = $object->pagination->pages;
echo $pages;
?>
Related
I have a json file stored on server & it looks like below:
{
"support_link":"#",
"support_link_2":"#",
"packs":[
{
"identifier":1,
"viewCount":0,
"downloadCount":0
},
{
"identifier":2,
"viewCount":0,
"downloadCount":0
}
]
}
By using PHP, I want to update the viewCount & downloadCount of some of the arrays inside packs.
But the thing is the data is received via a POST method to the server which contains another json with info. of which identifier to update & what param to update, & I am not able to update the existing file & save it back.
Received Json format:
{
"impressions": [
{
"identifier": "1",
"impressionCount": 2
},
{
"identifier": "100",
"impressionCount": 2
},
{
"identifier": "1000",
"impressionCount": 2000
}
],
"downloads": [
{
"identifier": "1",
"downloadCount": 10
}
]
}
What I've tried to do so far:
$json = file_get_contents('php://input');
if ($json != '') {
$properJsonFormatted = json_decode($json, true);
$impressions = $properJsonFormatted['impressions'];
$downloads = $properJsonFormatted['downloads'];
$testConfig =
$json = file_get_contents('php://input');
if ($json != '') {
$properJsonFormatted = json_decode($json, true);
$impressions = $properJsonFormatted['impressions'];
$downloads = $properJsonFormatted['downloads'];
$testConfig = json_decode(file_get_contents("test_config.json"),true);
$packs = $testConfig['packs'];
foreach ($packs as &$pack) {
$packIdentifier = $pack['identifier'];
foreach ($impressions as $impression) {
$impressionIdentifier = $impression['identifier'];
if ($packIdentifier == $impressionIdentifier) {
$pack['viewCount'] += $impression['impressionCount'];
$newCount = $pack['viewCount'];
print("Id: $packIdentifier, ViewCount: $newCount\n");
}
}
}
put_file_contents("test_config.json" , $testConfig);
// print_r($testConfig);
// Save back the updated test_config.json
}
}
UPDATE
Seem to have misinterpreted the question. The actual problem seems to be much simpler.
Change this:
put_file_contents("test_config.json" , $testConfig);
To this:
file_put_contents('test_config.json', json_encode($testConfig));
Also change this:
$packs = $testConfig['packs'];
To this:
$packs = &$testConfig['packs'];
As it seems you forgot to assign that by reference, while you correctly did that in the foreach.
I have json like this, returned from service:
{
"reports" : {
"name" : "reports"
"response" : {
"build" : {
"version" : "2.55.10.0",
"name" : "reports-app"
}
},
"status" : 200
},
"static-application" : {
"name" : "static-application"
"response" : {
"app" : {
"name" : "client-frontend",
"description" : "Client Static"
},
"build" : {
"version" : "2.55.10.0",
"name" : "client-frontend"
}
},
"status" : 200
},
"static-help" : {
"name" : "static-help"
"response" : {
"app" : {
"name" : "client-frontend",
"description" : "Client Static"
},
"build" : {
"version" : "2.55.8.0",
"name" : "client-frontend"
}
},
"status" : 200
}
}
And I'm trying to decode it with json_decode:
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, 'https://domainname/api/aggregate/info');
$json = curl_exec($ch);
curl_close($ch);
$data = json_decode($json, true);
echo $data['reports']['name']." | ".$data['reports']['response']['build']['version']."<br \>";
echo $data['static-application']['name']." | ".$data['static-application']['response']['build']['version']."<br \>";
echo $data['static-help']['name']." | ".$data['static-help']['response']['build']['version'];
?>
In return i have:
reports | 2.55.10.0
static-application | 2.55.10.0
static-help | 2.55.8.0
Everything works, but when the service will return more modules, I will have to manually add new echo sections.
How can I write the same in a loop?
You may use a foreach loop to iterate over all $data's modules:
$data = json_decode($json, true);
foreach($data as $module => $data)
{
if(isset($data[$module]['name']) && !empty($data[$module]['response']['build']['version']))
{
echo $data[$module]['name']." | ".$data[$module]['response']['build']['version']."<br \>";
}
}
The foreach let you iterate a single element at a time, without the need to manually handle how many elements it contains.
The empty function checks for the presence of the key in the array and if it contains, in the case it may be missed or empty.
If you want to dynamically output the name and build version of the JSON's sections you can use a foreach() loop to iterate over all items:
$data = json_decode($json);
foreach ( $data as $key => $jsonData ) {
echo $jsonData->name;
echo " | ";
echo $jsonData->response->build->version;
}
In my $output there is this:
{
"status" : "success",
"data" : {
"network" : "BTC",
"addresses" : [
{
"user_id" : 0,
"address" : "3ABR5GohqyXzf2zebYwjmLuwV7vtFZw1BZ",
"label" : "default",
"available_balance" : "0.00000000",
"pending_received_balance" : "0.00000000"
}
]
}
}
But now I want it to get to redirect like:
https://example.com/index.php?status=succes&network=BTC
etc. etc.
But $output can change to like:
{
"status" : "success",
"data" : {
"network" : "BTC",
"available_balance" : "0.00000000",
"pending_received_balance" : "0.00000000"
}
}
But then I still want it to work.
I don't know PHP enough for this, so I want to ask:
How to do this?
Simply json_decode() and access the status and network properties:
$decoded = json_decode($output);
header('Location: https://example.com/index.php?status=' . urlencode($decoded->status) . '&network=' . urlencode($decoded->data->network));
exit();
Get the data in the json as an array:
$url = 'https://example.com/index.php?status=' . $status;
foreach($data as $param->$value) {
$url += '&' . $param . '=' . $value
}
header('Location:' $url);
Been a while since i've worked in php but this should handle a varying amount of parameters.
I have a page where i get whole data from database
http://localhost/staff/home.php
if($btn_search =='Serach' && $btn_search !='') {
$search_field = isset($_GET['search_field'])?$_GET['search_field']:'';
$all_users = $obj->getAllUsers($search_field);
}else{
$all_users = $obj->getAllUsers();
$r = json_encode($all_users);
echo "<pre>";
print_r($r);
die();
}
here got the data in JSON format.
but now i want same data in other website and the path is
http://localhost/staff_json/
and the code i have done like this
<?php
$rs = file_get_contents('http://localhost/staff/home.php');
$obj = json_decode($rs);
echo "<pre>";
print_r($obj);
?>
the page is successfully run but data is not showing.
please help me if someone know this
In your http://localhost/staff/home.php in your else part:
else{
$all_users = $obj->getAllUsers();
$r = json_encode($all_users);
echo $r;
}
Updated my code as per your JSON:
put below JSON on "http://localhost/staff/home.php" as it is (actually this is your JSON output you are getting from your code)
[{
"id": "94",
"username": "jems",
"password": "123",
"email": "jems#gmail.com",
"mobile": "8596558499",
"address": "Banglor",
"gender": "male",
"salary": "0",
"status": "1",
"image_name": "1320294973-screenshot.jpg"
}, {
"id": "99",
"username": ".sapna",
"password": "sapna9",
"email": "sapnapapola15#gmail.com",
"mobile": "8826089668",
"address": "laxminagar",
"gender": "male",
"salary": "0",
"status": "1",
"image_name": "no-image.jpg"
}]
And below is the code your "http://localhost/staff_json/index.php"
<?php
$rs = file_get_contents("http://localhost/staff/home.php");
$obj = json_decode($rs);
echo "<pre>";
print_r($obj);
?>
I am getting the desired output
]3
AS per your code:
Prepare a separate file "userdata.php" place it to same folder where the "home.php" page /staff/userdata.php
<?php
include('config/controller.php');
$obj = new Controller();
$all_users = $obj->getAllUsers();
$r = json_encode($all_users);
echo $r;
?>
And below is the code your "http://localhost/staff_json/index.php"
<?php
$rs = file_get_contents("http://localhost/staff/userdata.php");
$obj = json_decode($rs);
echo "<pre>";
print_r($obj);
?>
Then you get the desired output:
Below is your "home.php" page PHP script:
<?php
include('config/controller.php');
$obj = new Controller();
include('header.php');
$obj->authenticate();
$all_users = '';
$search_field ='';
$btn_search = isset($_GET['btn_search'])?$_GET['btn_search']:'';
if($btn_search =='Serach' && $btn_search !='') {
$search_field = isset($_GET['search_field'])?$_GET['search_field']:'';
$all_users = $obj->getAllUsers($search_field);
}
?>
I removed your else part
Try this hope it will work for you
You need to echo you response
if($btn_search =='Serach' && $btn_search !='') {
$search_field = isset($_GET['search_field'])?$_GET['search_field']:'';
$all_users = $obj->getAllUsers($search_field);
}else{
$all_users = $obj->getAllUsers();
$r = json_encode($all_users);
echo $r;
}
Now hit the url.
AS per your comment you need the data of other project into your current project. So you need and CURL request to fetch the data from other project into your current one.
$ch = curl_init();
$curlConfig = array(
CURLOPT_URL => "http://localhost/staff/home.php",
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
);
curl_setopt_array($ch, $curlConfig);
$result = curl_exec($ch);
curl_close($ch);
$decodeData = json_decode($result);
print_r($decodeData);
Please try out the above code
Trying to get the single value from google finances api. I can retrieve the data perfectly however when I try to echo out a single value it doesn't seem to work. Can anyone help?
My code is:
$request = wp_remote_get('http://www.google.com/finance/info?q=NASDAQ%3aGOOG', $args );
$price = wp_remote_retrieve_body( $request );
print_r($price);
The output is:
// [
{
"id": "304466804484872"
,"t" : "GOOG"
,"e" : "NASDAQ"
,"l" : "533.75"
,"l_fix" : "533.75"
,"l_cur" : "533.75"
,"s": "2"
,"ltt":"4:01PM EST"
,"lt" : "Dec 2, 4:01PM EST"
,"lt_dts" : "2014-12-02T16:01:56Z"
,"c" : "-0.05"
,"c_fix" : "-0.05"
,"cp" : "-0.01"
,"cp_fix" : "-0.01"
,"ccol" : "chr"
,"pcls_fix" : "533.8"
,"el": "533.00"
,"el_fix": "533.00"
,"el_cur": "533.00"
,"elt" : "Dec 2, 7:59PM EST"
,"ec" : "-0.75"
,"ec_fix" : "-0.75"
,"ecp" : "-0.14"
,"ecp_fix" : "-0.14"
,"eccol" : "chr"
,"div" : ""
,"yld" : ""
}
]
I've tried echoing out the single value, adding a foreach statement and then echoing out the value based on 'l_fix' and the 'id', and also tried splitting the string up but it wouldn't work.
Thanks
Do it:
$request = wp_remote_get('http://www.google.com/finance/info?q=NASDAQ%3aGOOG', $args );
$data = wp_remote_retrieve_body( $request );
$data = str_replace('//','',$data);
$data = json_decode($data);
$price = $data[0]; // $price = array_shift($data);
print $price->l_fix .....
Google APIs (in this specific case) return JSON with two first chars ('//').