how to write a json file as a datasource in php? - php

I have some data like this
"name": "abc",
"adr": "bcd",
"partners": {
"101": {
"name": "xyz.com",
"prices": {
"1001": {
"description": "Single Room",
"amount": 125,
"from": "2012-10-12",
"to": "2012-10-13"
},
"1002": {
"description": "Double Room",
"amount": 139,
"from": "2012-10-12",
"to": "2012-10-13"
}
}
Now, I have to write a json with all this data and use it as a data source.
How can I do it ?

The data you posted is not valid JSON. It misses some surrounding and ending brackets.
Ok, let's fix that... and save it as data.json:
{
"name": "abc",
"adr": "bcd",
"partners": {
"101": {
"name": "xyz.com",
"prices": {
"1001": {
"description": "SingleRoom",
"amount": 125,
"from": "2012-10-12",
"to": "2012-10-13"
},
"1002": {
"description": "DoubleRoom",
"amount": 139,
"from": "2012-10-12",
"to": "2012-10-13"
}
}
}
}
}
To access the JSON with PHP you can simply load the file and convert the JSON to an array.
<?php
$jsonFile = "data.json"
$json = file_get_contents($jsonFile);
$data = json_decode($json, TRUE);
echo "<pre>";
print_r($data);
echo "</pre>";
?>

A PHP Script to create a file containing this data as json
// the data you need
$phpData = [
"name" => "abc",
"adr" => "bcd",
"partners" => [
"101" => [
"name" => "xyz.com",
"prices" => [
"1001" => [
"description" => "Single Room",
"amount" => 125,
"from" => "2012-10-12",
"to" => "2012-10-13",
],
"1002" => [
"description" => "Double Room",
"amount" => 139,
"from" => "2012-10-12",
"to" => "2012-10-13",
]
]
]
]
];
// json_encode() that data to a string
$jsonData = json_encode($phpData);
// write that string to your file
file_put_contents('myJsonFile.json', $jsonData);
And to use it as a datasource
$myData = json_decode(
file_get_contents('myJsonFile.json')
);

Related

Insert value in array after every index using php

I have fetch value from database and returning its array in json format. This is my code to get values. First array is working fine. But i need to add static array after every index in array. This is my code
$value = $this->TestModel->get_user_details($userIds);
this function returns array in json format e.g.
[
{
"user_id": "1",
"name": "test 1",
},
{
"user_id": "2",
"name": "test 2",
},
{
"user_id": "3",
"name": "test 3",
},
]
now i need to add below static json array with every item of array. This is e.g
$test1= array("student_list"=> array(array("stu_id"=>1, "name"=> "abc") , array("stu_id"=>2, "name"=> "xyz")),
"class"=> "12th",
"average_score"=>"5",
"results"=>array(array("result_date"=>"2012-12-13","city"=>"city 1"),array("result_date"=>"2015-10-13","city"=>"city 2")));
I have tried it with array_push and array_merge but it add this at the end end of array.
I need this Response
[
{
"user_id": "1",
"name": "test 1",
"student_list": [
{
"stu_id": 1,
"name": "abc",
},
{
"stu_id": 2,
"name": "xyz",
}
],
"class": "12th",
"average_score": "5",
"results": [
{
"result_date": "2012-12-13",
"city": "City 1",
},
{
"result_date": "2012-10-13",
"city": "City 2",
}
]
},
{
"user_id": "2",
"name": "test 2",
"student_list": [
{
"stu_id": 3,
"name": "asd",
},
{
"stu_id": 4,
"name": "ghj",
}
],
"class": "10th",
"average_score": "5",
"results": [
{
"result_date": "2011-12-13",
"city": "City 3",
},
{
"result_date": "2011-10-13",
"city": "City 4",
}
]
},
]
If you want to add $test1 to to every element you your array you should merge each element, like so:
$value = $this->TestModel->get_user_details($userIds);
$test1 = array(
"student_list" => array(array("stu_id" => 1, "name" => "abc"), array("stu_id" => 2, "name" => "xyz")),
"class" => "12th",
"average_score" => "5",
"results" => array(array("result_date" => "2012-12-13", "city" => "city 1"), array("result_date" => "2015-10-13", "city" => "city 2"))
);
$decoded = json_decode($value, true);
for ($i = 0; $i < count($decoded); $i++) {
$decoded[$i] = array_merge($decoded[$i], $test1);
}
$value = json_encode($decoded);

Podio is throwing PodioBadRequestError invalid_value int when trying to add an item that has multiple tags within its fields

I am trying to add a customer(Podio item) to my Podio app. This customer is being added programmatically from within a php application. There are several fields present on the customer: Name, Address, Email, Title, Phone Number, and an array of Tags. When a tag is added the color changes to highlight it.
In previous iterations I have been successful adding a different tag(newsletter_subscribed) using the ID of the tag value that I want highlighted. Now when I try to add another tag(hospital, clinic, or urgent_care) it is throwing a PodioBadRequestError. The error cited is that the ID being used is and invalid type(integer).
I got the values of the tag ID's by looking at the JSON returned when an existing customer created manually within my Podio customer application. When I look at the ID fields in the JSON they are most definitely integers, I have tried strings as well. Everything I try throws the 400 Bad Request on the ID that I am trying to add.
I cannot for the life of me figure out why it is throwing the error when I add the tag ID's.
Below is the way that the application is put together:
This is the code that builds and sends the request:
public function addToPodio()
{
$address = $this->Address . ", " .
$this->Address2 . ", " .
$this->City . ", " .
$this->State . " " .
$this->Zip;
$item = [
'fields' => [
'name' => $this->PrimaryContactFirstName,
'last-name' => $this->PrimaryContactLastName,
'email-address' => ['type' => 'work', 'value' => $this->PrimaryContactEmail],
'phone-number' => ['type' => 'work', 'value' => $this->PrimaryContactPhone],
'address' => $address,
'organization' => [$this->CompanyName],
'tags-2' => []
],
];
if ($this->Newsletter && defined('PODIO_NEWSLETTER_TAG_ID')){
$item['fields']['tags-2'][] = PODIO_NEWSLETTER_TAG_ID;
}
if($this->OrganizationType && defined('PODIO_ORGANIZATION_TYPE_ID')){
if($this->OrganizationType == "Clinic"){
$item['fields']['tags-2'][] = PODIO_ORGANIZATION_TYPE_CLINIC_TAG_ID;
}
else if($this->OrganizationType == "Hospital"){
$item['fields']['tags-2'][] = PODIO_ORGANIZATION_TYPE_HOSPITAL_TAG_ID;
}
try {
//This is where the request is being made
$customer = PodioItem::create(PODIO_CUSTOMER_APP_ID, $item);
$this->PodioId = $customer->item_id;
$this->write();
} catch (Exception $e) {
error_log('We encountered an error adding your item to Podio' . $e);
return 'An error occurred while updating Podio. Please try again. If the error...';
}
This is the PHP $item that is being passed to the request that gets sent to the Podio API:
Array
(
[fields] => Array
(
[name] => Joe
[last-name] => Test
[phone-number] => Array
(
[type] => work
[value] => 8675309
)
[address] => 123 Main Road, , East Test, NY 12345
[organization] => Array
(
[0] => Another Test
)
[tags-2] => Array
(
[0] => 16
[1] => 96
)
)
)
This is the config file with the all of the constants, secrets tokens and ID's needed to connect to the Podio API, authenticate and all of that stuff. Obfuscated Example below:
define('PODIO_CUSTOMER_APP_ID', 'xxxxx-obfuscated-xxxxx');
define('PODIO_CUSTOMER_APP_TOKEN', 'xxxxx-obfuscated-xxxxx');
define('PODIO_CLIENT_SECRET', 'xxxxx-obfuscated-xxxxx');
define('PODIO_CLIENT_ID', 'xxxxx-obfuscated-xxxxx');
define('PODIO_ORGANIZATION_TYPE_ID', 'xxxxx-obfuscated-xxxx');
define('PODIO_NEWSLETTER_TAG_ID', 'xxxxx-obfuscated-xxxxx');
define('PODIO_ORGANIZATION_TYPE_CLINIC_TAG_ID', 'xxxxx-obfuscated-xxxxx');
Podio::setup(PODIO_CLIENT_ID, PODIO_CLIENT_SECRET, [
'session_manager' => Injector::inst()->get(PodioSession::class),
'curl_options' => array(),
]);
Below is the JSON that I used to get the values of the ID's. I got this from a postman request to the API. The basic form of the request without all of the authentication present looked like:
podio.com/MY_PODIO_ACCOUNT_NAME/app/APPLICATION_ID/item/ITEM_ID
Please note: I removed many of the main fields like Address and Organization for brevity's sake, so it won't match completely the PHP request object above.
{
"id": 0000,
"item_id": 00000,
"revision": 0,
"app": null,
"app_item_id": 00000,
"app_item_id_formatted": "PODIO_Field_ID:00000",
"external_id": null,
"title": "TEST ITEM",
"fields": [
{
"id": 0000,
"field_id": 0000,
"type": "text",
"external_id": "name",
"label": "First Name",
"values": [
{
"value": "Joe"
}
],
"config": {
"settings": {
"format": "plain",
"size": "small"
},
"mapping": "contact_name",
"label": "First Name"
},
"humanized_value": "Joe"
},
{
"id": 0000,
"field_id": 0000,
"type": "text",
"external_id": "last-name",
"label": "Last Name",
"values": [
{
"value": "<p>Test<br /></p>"
}
],
"config": {
"settings": {
"format": "html",
"size": "large"
},
"mapping": null,
"label": "Last Name"
},
"humanized_value": "Test"
},
{
"id": 0000,
"field_id": 0000,
"type": "phone",
"external_id": "phone-number",
"label": "Phone Number",
"values": [
{
"type": "work",
"value": "867-5309"
}
],
"config": {
"settings": {
"call_link_scheme": "callto",
"possible_types": [
"mobile",
"work",
"home",
"main",
"work_fax",
"private_fax",
"other"
]
},
"mapping": "contact_phone",
"label": "Phone Number"
},
"humanized_value": "8675309"
},
{
"id": 11111,
"field_id": 11111,
"type": "category",
"external_id": "tags-2",
"label": "Tags",
"values": [
{
"value": {
"status": "active",
"text": "Clinic",
"id": 16,
"color": "DCEBD8"
}
},
{
"value": {
"status": "active",
"text": "Newlsetter_subscribed",
"id": 96,
"color": "DCEBD8"
}
}
],
"config": {
"settings": {
"multiple": true,
"options": [
{
"status": "active",
"text": "Mktng:test1/2020",
"id": 150,
"color": "DCEBD8"
},
{
"status": "active",
"text": "Mktng:Test2/2020",
"id": 3,
"color": "DCEBD8"
},
{
"status": "active",
"text": "SampleTest",
"id": 48,
"color": "DCEBD8"
},
{
"status": "deleted",
"text": "Test Center",
"id": 139,
"color": "DCEBD8"
},
{
"status": "deleted",
"text": "Sample Center",
"id": 99,
"color": "DCEBD8"
},
{
"status": "deleted",
"text": "Testing Center",
"id": 140,
"color": "DCEBD8"
}
],
"display": "inline"
},
"mapping": null,
"label": "Tags"
},
"humanized_value": "Clinic; Newsletter;"
}
this JSON continues for pages and pages, I only included the relevant fields for my question.
It looks like the error is being thrown because of the organization value, not the tags value.
For a category field, an array of integer indices is correct.
[tags-2] => [ 16, 96 ]
For an app field, you need to provide an array of integer item ID's.
[organization] => [ 12345 ]
But your code above is sending an array of strings:
[organization] => [ "Another Test" ]
That won't work.

How to write content as JSON format

I have a trouble with JSON in PHP.
I have a JSON structure like this (with some line is const and some line is variable)
{
"user": {
"lam": {---->variable
"\/lam\/files\/a": { ---->variable
"id": 9, ---->variable
"class": "\\OC\\Files\\Storage\\Swift",
"options": {
"user": "owncloud",
"bucket": "lam-15215156681752265498", ---->variable
"password": "",
"region": "regionOne",
"service_name": "swift",
"tenant": "owncloud",
"timeout": "30",
"url": "http:\/\/controller:5000\/v2.0",
"password_encrypted": "NHBuZHd4azhvZDB6b29oYSu5U7JLrDC3AdZGykzNpDU=" ---->variable
}
}
}
}
}
I don't know how to write this content to file as JSON format like this.
And in a number of case, I must write append to this file and result must like this:
{
"user": {
"lam": {
"\/lam\/files\/a": {
"id": 9,
"class": "\\OC\\Files\\Storage\\Swift",
"options": {
"user": "owncloud",
"bucket": "lam-15215156681752265498",
"password": "",
"region": "regionOne",
"service_name": "swift",
"tenant": "owncloud",
"timeout": "30",
"url": "http:\/\/controller:5000\/v2.0",
"password_encrypted": "NHBuZHd4azhvZDB6b29oYSu5U7JLrDC3AdZGykzNpDU="
}
},
"\/lam\/files\/test": {
"id": 12,
"class": "\\OC\\Files\\Storage\\Swift",
"options": {
"user": "owncloud",
"bucket": "lam-152153961597103330",
"password": "",
"region": "regionOne",
"service_name": "swift",
"tenant": "owncloud",
"timeout": "30",
"url": "http:\/\/controller:5000\/v2.0",
"password_encrypted": "MjdzcDlrenptcG5udzI2MLSQvuGIczY\/SyHZVf9o7e8="
}
}
}
}
}
You could create an array, before to use json_encode():
Here is an example.
// prepare an array with variable (should come from database, or whatever)
$vars = [
[
'user' => 'lam',
'path' => '/lam/files/a',
'id' => 9,
'bucket' => 'lam-15215156681752265498',
'pass' => 'NHBuZHd4azhvZDB6b29oYSu5U7JLrDC3AdZGykzNpDU=',
],
[
'user' => 'lam',
'path' => '/lam/files/test',
'id' => 12,
'bucket' => 'lam-152153961597103330',
'pass' => 'MjdzcDlrenptcG5udzI2MLSQvuGIczY/SyHZVf9o7e8=',
]
];
// prepare data to be encoded.
$data = [];
// iterate over the variables,
foreach ($vars as $var) {
// prepare an array for the options
$options = [
"user" => "owncloud",
"bucket" => $var['bucket'], // fill with current variable
"password" => "",
"region" => "regionOne",
"service_name" => "swift",
"tenant" => "owncloud",
"timeout" => "30",
"url" => "http:\/\/controller:5000\/v2.0",
"password_encrypted" =>$var['pass'], // fill with current variable
];
$userdata = [
'id' => $var['id'], // fill with current variable
'class' => '\\OC\\Files\\Storage\\Swift',
'options' => $options, // append options
];
$name = $var['user'];
$path = $var['path'];
$data['user'][$name][$path] = $userdata ; // append to $data array
}
echo json_encode($data, JSON_PRETTY_PRINT);
Outputs:
{
"user": {
"lam": {
"\/lam\/files\/a": {
"id": 9,
"class": "\\OC\\Files\\Storage\\Swift",
"options": {
"user": "owncloud",
"bucket": "lam-15215156681752265498",
"password": "",
"region": "regionOne",
"service_name": "swift",
"tenant": "owncloud",
"timeout": "30",
"url": "http:\\\/\\\/controller:5000\\\/v2.0",
"password_encrypted": "NHBuZHd4azhvZDB6b29oYSu5U7JLrDC3AdZGykzNpDU="
}
},
"\/lam\/files\/test": {
"id": 12,
"class": "\\OC\\Files\\Storage\\Swift",
"options": {
"user": "owncloud",
"bucket": "lam-152153961597103330",
"password": "",
"region": "regionOne",
"service_name": "swift",
"tenant": "owncloud",
"timeout": "30",
"url": "http:\\\/\\\/controller:5000\\\/v2.0",
"password_encrypted": "MjdzcDlrenptcG5udzI2MLSQvuGIczY\/SyHZVf9o7e8="
}
}
}
}
}
You'll need to work with the data as an array (or object) as PHP won't work directly in JSON;
Get your current data from the file into an array:
$data = json_decode(file_get_contents($pathtojsonfile, true));
Append the new data to the array:
$data[] = $newdata;
Then save the newly appended data back to file.
file_put_contents($pathtojsonfile, json_encode($data));

Nested JSON Object with array in PHP

I want JSON object as follows in that personal, address and itm have sequence of json object.
{
"id": "1",
"state": "12",
"personal": [
{
"name": "abc",
"contact":"1111111"
"address": [
{
"line1": "abc",
"city": "abc",
"itm": [
{
"num": 1,
"itm_detatils": {
"itemname": "bag",
"rate": 1000,
"discount": 0,
}
}
],
"status": "Y"
}
]
}
]
}
But I am getting result as follows in that I want json array at address and itm_details.
{
"id": "1",
"state": "12",
"personal": [
{
"name": "abc",
"contact": "1111111",
"address": {
"line1": "abc",
"city": "abc",
"itm": {
"inum": "1",
"itm_detatils": {
"itemname": "bag",
"rate": 1000,
"discount": 0
}
},
"status": "Y"
}
}
]
}
My PHP Code is as follow:
In that I am creating simple array and after that array inside array but during encoding to json it's not showing sequence of json object.
$a=array();
$a["id"]="1";
$a["state"]="12";
$a["personal"]=array();
$a["personal"][]=array(
"name"=>"abc",
"contact"=>"1111111",
"address"=>array(
"line1"=>"abc",
"city"=>"abc",
"itm"=>array(
"inum"=>"1",
"itm_detatils"=>array(
"itemname"=>"bag",
"rate"=>1000,
"discount"=>0,
),
),
"status"=>"Y",
),
);
echo json_encode($a);
Thanks in advance.
Add one more array
//...
"address" => array(
array(
"line1"=>"abc",
"city"=>"abc",
// ...
),
)

How to Name a RESTLER json Result

Forgive my terminology im a newbie in in web dev.
To visualize my question, see below.
This is how RESTLER displays json:
[
{
"id": 1,
"name": "Daniel Craig",
"email": "dc#gmail.com"
},
{
"id": 2,
"name": "Tom Cruise",
"email": "tc#gmail.com"
}
]
This is how i would want RESTLER to display json results:
{"actors":[
{
"id": 1,
"name": "Daniel Craig",
"email": "dc#gmail.com"
},
{
"id": 2,
"name": "Tom Cruise",
"email": "tc#gmail.com"
}
]}
Just wrap your result with another array. if we assume that $result returns the first result above, do the following
$result = array(
array(
"id" => 1,
"name" => "Daniel Craig",
"email" => "dc#gmail.com"
),
array(
"id" => 2,
"name" => "Tom Cruise",
"email" => "tc#gmail.com"
)
);
return array('actors'=>$result);

Categories