Recognizing JSON Content - php

I have the following data
{
total: "156",
list: [
{
"nodeRef": "workspace://SpacesStore/e364714d-14bc-4e13-bfff-c1f86a8cbe67",
"id": "e364714d-14bc-4e13-bfff-c1f86a8cbe67",
"name": "Morning Class_Dadi Janki_29-05-12_H_London.mp4",
"mimetype": "video/mp4",
"title" : "Morning Class" ,
"author": "Dadi Janki",
"class_date": "May 29, 2012 12:00:00 AM",
"created": "May 29, 2012 12:32:44 PM",
"size": "97,156,420",
"lang": "h",
"totalViews": "11",
"totalDownloads": "0",
"downloadUrl": "/d/a/workspace/SpacesStore/e364714d-14bc-4e13-bfff-c1f86a8cbe67/Morning%20Class_Dadi%20Janki_29-05-12_H_London.mp4"
}
]
}
When I try to var_dump it
It gives me null. How do I know whether the data is JSON encoded or not ?
Edit:
Here's the code
I get the above content by get_contents to the url
$url = ""; // URL
$contents = file_get_contents($url);
$data = json_decode($contents);
var_dump($data);

<?php
$str = '{
total: "156",
list: [
{
"nodeRef": "workspace://SpacesStore/e364714d-14bc-4e13-bfff-c1f86a8cbe67",
"id": "e364714d-14bc-4e13-bfff-c1f86a8cbe67",
"name": "Morning Class_Dadi Janki_29-05-12_H_London.mp4",
"mimetype": "video/mp4",
"title" : "Morning Class" ,
"author": "Dadi Janki",
"class_date": "May 29, 2012 12:00:00 AM",
"created": "May 29, 2012 12:32:44 PM",
"size": "97,156,420",
"lang": "h",
"totalViews": "11",
"totalDownloads": "0",
"downloadUrl": "/d/a/workspace/SpacesStore/e364714d-14bc-4e13-bfff-c1f86a8cbe67/Morning%20Class_Dadi%20Janki_29-05-12_H_London.mp4"
}
]
}
';
$str = preg_replace('#([^\s\"]+): #is', '"\\1": ', $str);
echo $str;
?>

First whenever you will get any json value or you are sending any value in json format first check whether Json is valid or not..
Json validator and formator:-
http://jsonformatter.curiousconcept.com/
Json validator:-
http://www.jsonlint.org/
Then in Your code try to find error :- json_last_error
And try to use Json encode and Decode for Url values.. that will be helpful always..
Valid Json:-
{
"total":"156",
"list":[
{
"nodeRef":"workspace://SpacesStore/e364714d-14bc-4e13-bfff-c1f86a8cbe67",
"id":"e364714d-14bc-4e13-bfff-c1f86a8cbe67",
"name":"Morning Class_Dadi Janki_29-05-12_H_London.mp4",
"mimetype":"video/mp4",
"title":"Morning Class",
"author":"Dadi Janki",
"class_date":"May 29, 2012 12:00:00 AM",
"created":"May 29, 2012 12:32:44 PM",
"size":"97,156,420",
"lang":"h",
"totalViews":"11",
"totalDownloads":"0",
"downloadUrl":"/d/a/workspace/SpacesStore/e364714d-14bc-4e13-bfff-c1f86a8cbe67/Morning%20Class_Dadi%20Janki_29-05-12_H_London.mp4"
}
]
}
Json:--
{"total":"156","list":[{"nodeRef":"workspace://SpacesStore/e364714d-14bc-4e13-bfff-c1f86a8cbe67","id":"e364714d-14bc-4e13-bfff-c1f86a8cbe67","name":"Morning Class_Dadi Janki_29-05-12_H_London.mp4","mimetype":"video/mp4","title":"Morning Class","author":"Dadi Janki","class_date":"May 29, 2012 12:00:00 AM","created":"May 29, 2012 12:32:44 PM","size":"97,156,420","lang":"h","totalViews":"11","totalDownloads":"0","downloadUrl":"/d/a/workspace/SpacesStore/e364714d-14bc-4e13-bfff-c1f86a8cbe67/Morning%20Class_Dadi%20Janki_29-05-12_H_London.mp4"}]}

Related

Filtering Out Data Returned by an API by Date

I have data returned by an API that I'm looping through and populating a table with. I'm only interested in the data that is from the last thirty days.
I've written some code that takes today's date, subtracts 30 days from it and stores the result. It then creates a new array, loops through the API data and compares the date of each entry, disregarding anything that falls outside the boundaries.
$response = curl_exec($curl);
$err = curl_error($curl);
$responseResult = json_decode($response, true);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
$today = date('Y-m-j');
$newdate = strtotime ( '-30 days' , strtotime ( $today ) ) ;
$newdate = date ( 'Y-m-j' , $newdate );
foreach($responseResult as $subject) {
$createdDate = $subject['created_at'];
if($createdDate < $newdate) {
$filteredThirtyDays[] = $createdDate;
}
}
return count($filteredThirtyDays);
This doesn't work. My logic is wrong.
Sample Data
{
"id": "5cf65651bbddbd5462599808",
"number": 4551,
"user_id": "5b8425c8e694aa3c6a835b67",
"state": "closed",
"subject": "Database",
"label_ids": [
"5c49b2d9bbddbd17834bbff6"
],
"customer_id": "5b52f0cabbddbd01c5bdd6c8",
"type": "email",
"reply_to": "user#domain.com",
"reply_cc": "",
"group_id": "5a5f65fed5593070120b9779",
"inbox_id": "5a5f65fed5593070120b9779",
"updated_at": "2019-06-04T13:41:58Z",
"created_at": "2019-06-04T11:30:25Z",
"spam": false,
"trash": false,
"summary": "",
"rating": null,
"waiting_since": "2019-06-04T12:56:05Z"
},
{
"id": "5cf6561ebbddbd28217a0b89",
"number": 4550,
"user_id": "5b51bf13bbddbd7e6248c934",
"state": "closed",
"subject": "Exchange",
"label_ids": [
"5c4b0cf4bbddbd48cd69e68a"
],
"customer_id": "5b51fdf1bbddbd5f4575a428",
"type": "phone",
"reply_to": "user#domain.com",
"reply_cc": "",
"group_id": "5a5f65fed5593070120b9779",
"inbox_id": "5a5f65fed5593070120b9779",
"updated_at": "2019-06-04T12:49:06Z",
"created_at": "2019-06-04T11:29:35Z",
"spam": false,
"trash": false,
"summary": "Hi Chris Might have been the user name",
"rating": null,
"waiting_since": "2019-06-04T12:41:08Z"
}
]
What I want is a count of how many items are within the thirty day period. What I'm getting is all results from all dates.
EDIT :
I THINK the issue is the time format. The API is returning the date as a string, formatted as 2019-06-04T12:49:06Z. When I do echo strtotime('2019-06-04T12:49:06Z'); it returns 1559652546, which is what is being compared.
So, I think I need to convert the Zulu time format into something I can use to compare...
Check if this works for your.
<? php
$responseResult = '[{
"id" : "5cf65651bbddbd5462599808",
"number": 4551,
"user_id": "5b8425c8e694aa3c6a835b67",
"state": "closed",
"subject": "Database",
"label_ids": [
"5c49b2d9bbddbd17834bbff6"
],
"customer_id": "5b52f0cabbddbd01c5bdd6c8",
"type": "email",
"reply_to": "user#domain.com",
"reply_cc": "",
"group_id": "5a5f65fed5593070120b9779",
"inbox_id": "5a5f65fed5593070120b9779",
"updated_at": "2019-06-04T13:41:58Z",
"created_at": "2019-06-04T11:30:25Z",
"spam": false,
"trash": false,
"summary": "",
"rating": null,
"waiting_since": "2019-06-04T12:56:05Z"
}, {
"id": "5cf6561ebbddbd28217a0b89",
"number": 4550,
"user_id": "5b51bf13bbddbd7e6248c934",
"state": "closed",
"subject": "Exchange",
"label_ids": [
"5c4b0cf4bbddbd48cd69e68a"
],
"customer_id": "5b51fdf1bbddbd5f4575a428",
"type": "phone",
"reply_to": "user#domain.com",
"reply_cc": "",
"group_id": "5a5f65fed5593070120b9779",
"inbox_id": "5a5f65fed5593070120b9779",
"updated_at": "2019-06-04T12:49:06Z",
"created_at": "2019-05-04T11:29:35Z",
"spam": false,
"trash": false,
"summary": "Hi Chris Might have been the user name",
"rating": null,
"waiting_since": "2019-06-04T12:41:08Z"
}]
';
$today = date('Y-m-j');
$filteredThirtyDays = array();
$responseResultArr = json_decode($responseResult);
foreach($responseResultArr as $created => $date) {
$nDate = (array) $date;
if (strtotime($nDate['created_at']) <= strtotime('-30 days')) {
$filteredThirtyDays[] = $date;
}
}
print_r($filteredThirtyDays);

How to Modify Json Response get as object to array?

this is json response:
{
"level1": {
"level2":
{
"name": "abc",
"age": "19",
"email": "abc#g.com",
"gender": "Female",
"dob": "7 june 1999",
"add": "sdasdadas"
}
}
}
I want to convert JSON response as following way:
{
"level1": {
"level2":
[{
"name": "abc",
"age": "19",
"email": "abc#g.com",
"gender": "Female",
"dob": "7 june 1999",
"add": "sdasdadas"
}]
}
}
I converted my XML response into JSON form and get the object if I have one user details in level2 but I want it in an array in level 2 even have multiple user details or single user details..how can be possible?
Please try this code as #simonecosci mentioned in the comment.
$responseData ='{
"level1": {
"level2":
{
"name": "abc",
"age": "19",
"email": "abc#g.com",
"gender": "Female",
"dob": "7 june 1999",
"add": "sdasdadas"
}
}
}';
$json = json_decode($responseData);
$json->level1->level2 = [$json->level1->level2];
echo '<pre>';
print_r(json_encode($json));
echo '</pre>';
Expected output:
{"level1":{"level2":[{"name":"abc","age":"19","email":"abc#g.com","gender":"Female","dob":"7
june 1999","add":"sdasdadas"}]}}

How to save JSON into ini-file with php?

I have a datastream as JSON, I want to parse it and want to save result in ini-file :
{
"books": [{
"id": "1",
"date": "2017-03-12",
"date_text": "sunday 12 march",
"title": "title text"
}, {
"id": "2",
"date": "2017-03-12",
"date_text": "sunday 12 march",
"title": "title text"
}]
}
This is my sample data and I would like to know if there is a way to save it into a file no matter if it contain 1 or more "id:s" (Items)
I know how to parse the JSON but not how to save it down to a file in correct format for an ini.
Preferable format:
[Books 0]
id= 1
date= 2017-03-12
date_text=sunday 12 march
title= title text
[Books 1]
id"=2
date=2017-03-12
date_text=sunday 12 march
title=title text
You can try Zend Config for this task. Open your terminal and add zend-config to your project as dependency (assuming you already using composer):
composer require zendframework/zend-config
Now you can try following,
$json = <<<JSON
{
"books": [{
"id": "1",
"date": "2017-03-12",
"date_text": "sunday 12 march",
"title": "title text"
}, {
"id": "2",
"date": "2017-03-12",
"date_text": "sunday 12 march",
"title": "title text"
}]
}
JSON;
$config = new \Zend\Config\Config(json_decode($json, true), true);
$writer = new \Zend\Config\Writer\Ini();
echo $writer->toString($config);
The output will be:
[books]
0.id = "1"
0.date = "2017-03-12"
0.date_text = "sunday 12 march"
0.title = "title text"
1.id = "2"
1.date = "2017-03-12"
1.date_text = "sunday 12 march"
1.title = "title text"
Your JSON format should be look like below to produce desired output you wrote in question:
{
"books 0": {
"id": "1",
"date": "2017-03-12",
"date_text": "sunday 12 march",
"title": "title text"
},
"books 1" : {
"id": "2",
"date": "2017-03-12",
"date_text": "sunday 12 march",
"title": "title text"
}
}

JSON decode without double quotes for the string

c_id: 76523456,
output: {
alert_level: 1,
data: {
volume: 56,
date: '10th June 2016'
},
alert_level: 2,
data: {
volume: 26,
date: '10th July 2016'
}
}
}
Can someone please help. How can we apply double quotes via php code, then decode it?
if i am not wrong this should be the structure of json what you are expecting ...
[{
"alert_level": 1,
"data": {
"volume": 56,
"date": "10th June 2016"
}
}, {
"alert_level": 2,
"data": {
"volume": 26,
"date": "10th July 2016"
}
}]
dict inside the list/Array

Display JSON response using PHP from URL

I have a feed from a parcel tracking service that i am trying to integrate into my site. I have a url which allows me to put the tracking number at the end and get a json response. I have multiple objects from this which include some static info such as the senders address and some info which I will need to use a foreach for like the tracking progress.
I believe I have got the string okay however I am not sure how I am meant to display the info.
This is what I have so far:
Example URL:
domain.com/REST_Service/webservice/consignee/SelfshipService.svc/web/Tracking/84941354665
URL Returns:
{
"Agent": null,
"Consignee": {
"Address1": "25 HEATHFIELD ROAD",
"Address2": "SHOLING",
"Address3": "",
"Code": null,
"Company": "ERIK HANSON",
"Country": "GREAT BRITAIN",
"Dept": "",
"Email": "ERIK.HANSON66#GOOGLEMAIL.COM",
"Name": "",
"Phone": "07770320490",
"Postcode": "SO19 1DL",
"State": "HANTS",
"Town": "SOUTHAMPTON"
},
"CrossIdx": "",
"Error": null,
"NonDel": null,
"POD": {
"Date": "13 Jul 2016",
"Status": "Harnett",
"Time": "09:17"
},
"Pieces": 1,
"PosErr": 0,
"Tracks": [
{
"Date": "13 Jul 2016",
"Status": "Out for delivery",
"Time": "07:10"
},
{
"Date": "13 Jul 2016",
"Status": "At Delivery location Portsmouth",
"Time": "02:24"
},
{
"Date": "13 Jul 2016",
"Status": "At Delivery location Portsmouth",
"Time": "02:22"
},
{
"Date": "12 Jul 2016",
"Status": "Arrived At Ryton",
"Time": "22:12"
},
{
"Date": "12 Jul 2016",
"Status": "Preparing for despatch",
"Time": "14:00"
},
{
"Date": "12 Jul 2016",
"Status": "Scanned into OCS HEATHROW LONDON",
"Time": "13:59"
},
{
"Date": "12 Jul 2016",
"Status": "Consignment details verified",
"Time": "13:59"
},
{
"Date": "14 Jun 2016",
"Status": "Shipment prepared by customer",
"Time": "11:20"
},
{
"Date": "02 Jan 2003",
"Status": "Collected from Customer",
"Time": "09:32"
}
],
"Weight": 7
}
Current PHP:
//set tracking url
$url = "http://www.ocscourier.co.uk/REST_Service/webservice/consignee/SelfshipService.svc/web/Tracking/84941354665";
// create curl resource
$ch = curl_init();
// set url
curl_setopt($ch, CURLOPT_URL, "http://www.ocscourier.co.uk/REST_Service/webservice/consignee/SelfshipService.svc/web/Tracking/84941354665");
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');
// $output contains the output string
$output = curl_exec($ch);
// close curl resource to free up system resources
curl_close($ch);
//call api
//$json = file_get_contents($url);
$json = json_decode($output);
$Address1 = $json->results[0]->Consignee->Address1;
$Address2 = $json->results[0]->Consignee->Address2;
echo "Address 1: " . $Address1 . ", Address 2: " . $Address2;
Your json string doesn't have any results key (so I'm not sure why you trying to access results[0].
You can just use
$Address1 = $json->Consignee->Address1;
$Address2 = $json->Consignee->Address2;
Check this code:
$s = <<< END
{
"Agent": null,
"Consignee": {
"Address1": "25 HEATHFIELD ROAD",
"Address2": "SHOLING",
"Address3": "",
"Code": null,
"Company": "ERIK HANSON",
"Country": "GREAT BRITAIN",
"Dept": "",
"Email": "ERIK.HANSON66#GOOGLEMAIL.COM",
"Name": "",
"Phone": "07770320490",
"Postcode": "SO19 1DL",
"State": "HANTS",
"Town": "SOUTHAMPTON"
},
"CrossIdx": "",
"Error": null,
"NonDel": null,
"POD": {
"Date": "13 Jul 2016",
"Status": "Harnett",
"Time": "09:17"
},
"Pieces": 1,
"PosErr": 0,
"Tracks": [
{
"Date": "13 Jul 2016",
"Status": "Out for delivery",
"Time": "07:10"
},
{
"Date": "13 Jul 2016",
"Status": "At Delivery location Portsmouth",
"Time": "02:24"
},
{
"Date": "13 Jul 2016",
"Status": "At Delivery location Portsmouth",
"Time": "02:22"
},
{
"Date": "12 Jul 2016",
"Status": "Arrived At Ryton",
"Time": "22:12"
},
{
"Date": "12 Jul 2016",
"Status": "Preparing for despatch",
"Time": "14:00"
},
{
"Date": "12 Jul 2016",
"Status": "Scanned into OCS HEATHROW LONDON",
"Time": "13:59"
},
{
"Date": "12 Jul 2016",
"Status": "Consignment details verified",
"Time": "13:59"
},
{
"Date": "14 Jun 2016",
"Status": "Shipment prepared by customer",
"Time": "11:20"
},
{
"Date": "02 Jan 2003",
"Status": "Collected from Customer",
"Time": "09:32"
}
],
"Weight": 7
}
END;
$json = json_decode($s);
$Address1 = $json->Consignee->Address1;
$Address2 = $json->Consignee->Address2;
echo "Address 1: " . $Address1 . ", Address 2: " . $Address2;
Here is the output:
Address 1: 25 HEATHFIELD ROAD, Address 2: SHOLING
Below is json string in $json variable and access with RecursiveIteratorIterator
Example
$json='{
"Agent": null,
"Consignee": {
"Address1": "25 HEATHFIELD ROAD",
"Address2": "SHOLING",
"Address3": "",
"Code": null,
"Company": "ERIK HANSON",
"Country": "GREAT BRITAIN",
"Dept": "",
"Email": "ERIK.HANSON66#GOOGLEMAIL.COM",
"Name": "",
"Phone": "07770320490",
"Postcode": "SO19 1DL",
"State": "HANTS",
"Town": "SOUTHAMPTON"
},
"CrossIdx": "",
"Error": null,
"NonDel": null,
"POD": {
"Date": "13 Jul 2016",
"Status": "Harnett",
"Time": "09:17"
},
"Pieces": 1,
"PosErr": 0,
"Tracks": [
{
"Date": "13 Jul 2016",
"Status": "Out for delivery",
"Time": "07:10"
},
{
"Date": "13 Jul 2016",
"Status": "At Delivery location Portsmouth",
"Time": "02:24"
},
{
"Date": "13 Jul 2016",
"Status": "At Delivery location Portsmouth",
"Time": "02:22"
},
{
"Date": "12 Jul 2016",
"Status": "Arrived At Ryton",
"Time": "22:12"
},
{
"Date": "12 Jul 2016",
"Status": "Preparing for despatch",
"Time": "14:00"
},
{
"Date": "12 Jul 2016",
"Status": "Scanned into OCS HEATHROW LONDON",
"Time": "13:59"
},
{
"Date": "12 Jul 2016",
"Status": "Consignment details verified",
"Time": "13:59"
},
{
"Date": "14 Jun 2016",
"Status": "Shipment prepared by customer",
"Time": "11:20"
},
{
"Date": "02 Jan 2003",
"Status": "Collected from Customer",
"Time": "09:32"
}
],
"Weight": 7
}';
$jsonIterator = new RecursiveIteratorIterator(
new RecursiveArrayIterator(json_decode($json, TRUE)),
RecursiveIteratorIterator::SELF_FIRST);
foreach ($jsonIterator as $key => $val) {
if(is_array($val)) {
echo "$key:\n</br>";
} else {
echo "$key => $val\n";
}
}
OUTPUT:
Agent => Consignee:
Address1 => 25 HEATHFIELD ROAD Address2 => SHOLING Address3 => Code => Company => ERIK HANSON Country => GREAT BRITAIN Dept => Email => ERIK.HANSON66#GOOGLEMAIL.COM Name => Phone => 07770320490 Postcode => SO19 1DL State => HANTS Town => SOUTHAMPTON CrossIdx => Error => NonDel => POD:
Date => 13 Jul 2016 Status => Harnett Time => 09:17 Pieces => 1 PosErr => 0 Tracks:
0:
Date => 13 Jul 2016 Status => Out for delivery Time => 07:10 1:
Date => 13 Jul 2016 Status => At Delivery location Portsmouth Time => 02:24 2:
Date => 13 Jul 2016 Status => At Delivery location Portsmouth Time => 02:22 3:
Date => 12 Jul 2016 Status => Arrived At Ryton Time => 22:12 4:
Date => 12 Jul 2016 Status => Preparing for despatch Time => 14:00 5:
Date => 12 Jul 2016 Status => Scanned into OCS HEATHROW LONDON Time => 13:59 6:
Date => 12 Jul 2016 Status => Consignment details verified Time => 13:59 7:
Date => 14 Jun 2016 Status => Shipment prepared by customer Time => 11:20 8:
Date => 02 Jan 2003 Status => Collected from Customer Time => 09:32 Weight => 7

Categories