This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 5 years ago.
Some fields save data in the following way in one of my database field:
{"per_meter_en-GB":"TEST_FOR_TEST","roll_40_en-GB":"","ask_for_price_en-GB":"YES"}
(* Don't know how it's called so i wrote string in the title)
How can i access data in particular for every "value".
One way could be to explode for every field but is there a better way to do this?
$ask_for_price_variable = [value from field];
if ($ask_for_price_variable == 'YES') {
// Do something
}
EDIT: As i said i did not know how it was called "JSON" so i could not search for it. Thank you all for the answers.
It is json data. You can access it using json_decode in php
$json = '{"per_meter_en-GB":"TEST_FOR_TEST","roll_40_en-GB":"","ask_for_price_en-GB":"YES"}';
$data = json_decode($json,true);
$ask_for_price_variable = $data['ask_for_price_en-GB'];
Use json_decode
$str = '{"per_meter_en-GB":"TEST_FOR_TEST","roll_40_en-GB":"","ask_for_price_en-GB":"YES"}';
print_r(json_decode($str, true));
You need to study about JSON type and how to encode or decode to get the data.
try this
echo "<pre>";
print_r( json_decode('{"per_meter_en-GB":"TEST_FOR_TEST","roll_40_en-GB":"","ask_for_price_en-GB":"YES"}'));
to view the result , click run or hit f9, here
try json_decode function
$str = '{"per_meter_en-GB":"TEST_FOR_TEST","roll_40_en-GB":"","ask_for_price_en-GB":"YES"}';
$data = json_decode($str, true);
print_r($data);
output:
Array ( [per_meter_en-GB] => TEST_FOR_TEST [roll_40_en-GB] => [ask_for_price_en-GB] => YES )
here you can access required value from $data array eg. echo $data['per_meter_en-GB']; will output TEST_FOR_TEST
Related
This question already has answers here:
json_decode to array
(12 answers)
Closed 2 years ago.
I am trying to access the fields of a JSON-File. The JSON look like:
{"ip":"83.215.135.170","location:"{"country":"AT","region":"Salzburg","city":"Salzburg","lat":47.8125,"lng":13.0504,"postalCode":"5020"
I want to access the latitude and longitude of this file. My current code looks like that:
$data = json_decode($json);
echo $data["location:"]["lat"];
I get the error that the index is undefined. Can anybody help me?
You have a corupted JSON...here is the correct one
$json = '$json = '{"ip":"83.215.135.170","location":{"country":"AT","region":"Salzburg","city":"Salzburg","lat":47.8125,"lng":13.0504,"postalCode":"5020"}}';
With correct JSON you do this:
$decodedJson = json_decode($json,true);
And now you can do this:
echo $decodedJson["location"]["lat"]; // Prints 47.8125
if you want to access the fields like an array, you got to add "true" as a second parameter.
https://www.php.net/manual/de/function.json-decode.php
$data = json_decode($json, true);
echo $data["location:"]["lat"];
This question already has answers here:
How to create a JSON object
(5 answers)
Closed 3 years ago.
I have the following PHP code, which gets executed when I hit the Submit button in a form:
// Save data
if(isset($_POST['save'])){
$newDataArr = array();
foreach ($data_array[0] as $k=>$v){
$newDataArr[] = array($k => $_POST[$k]);
}// ./ foreach
echo json_encode($newDataArr);
}
The echo I get is the following:
[{"ID->id":"esKZSCDfIC"},{"DT->createdAt":"2020-01-26T13:02:42"},{"DT->updatedAt":"2020-01-26T13:02:42"},{"ST->aString":"hey1"},{"NU->number":123},{"GPS->coords":["2.2222","44.4444"]},{"BL->aBool":false},{"AR->theArray":["xx","ww"]},{"FL->theFile":"https:\/\/xscoder.com\/xserver\/uploads\/6dydDtoTt5JjZzFc5L5V_image.jpg"},{"PO->userPointer":"vbN3b0C7bC"}]
Then I'll have to add that array into my JSON file as it follows:
$data = json_encode(array_values($newDataArr), JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
file_put_contents('Test.json', $data);
But of course the syntax of my $newDataArr is not the right one, each JSON object must not be inside the { }, so this:
{"ID->id":"esKZSCDfIC"},
must become:
"ID->id":"esKZSCDfIC",
Is there a way to dynamically create a valid JSON array and push it to my Test.json file?
I've been through many posts on StackOverflow, but the result I get is always the same. I must use the PHP code above to get keys and values from my HTML inputs.
Instead of creating and pushing a new array on each iteration, set the values this way:
$newDataArr[$k] = $_POST[$k];
Hope this helps.
This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 6 years ago.
So I've been stumped and I'm not sure how I would continue this
as an example let's just use books.com as the URL and let's say the JSON response from the URL is
[{"title":"first_title","description":"second_title"},
{"title":"second_title","description":"second_description"}]
How would I print all of the titles (just the titles) without knowing exactly how many there are.
I know that I would need to loop through the JSON but I'm unsure how, if I could have any guidance that would be fantastic.
You should get more familiar with json_decode() and foreach().
First you need to decode json (into array in this example) and then iterate through all elements.
Example of working code:
<?php
$json = '[{"title":"first_title","description":"second_title"},
{"title":"second_title","description":"second_description"}]';
$jsonArray = json_decode($json,true);
foreach($jsonArray as $entry) {
echo $entry['title'].'<br>';
}
Output:
first_title
second_title
This key is to actually convert the JSON response into a PHP associative array by using json_decode and then loop through it.
// Convert the JSON into a PHP associative Array
$response = json_decode($curlResponse,true);
// Loop through the array
foreach ($response as $value) {
echo $value['title'];
echo '<br/>';
}
This question already has answers here:
Append data to JSON array using PHP
(3 answers)
Closed 4 months ago.
I am trying to call array_push to add data sent via a GET request to my json array that holds registration ids for my GCM Clients
<?php
//read current regids
$myfile = fopen("regids.json", "r") or die("Unable to open file!");
$current_regids = fread($myfile,filesize("regids.json"));
// decode json
$decoded_json= json_decode($current_regids);
//save to php format array
$array = array($decoded_json);
//close file
fclose($myfile);
//get registration id
$regid = $_GET["regid"];
//push new reg id into array
array_push($array,$regid);
echo json_encode($array);
?>
The JSON should be as follows
["regid1","regid2", "regid3","regid4"]
However when I run the code it inorder to array_push "regid5" it gives me this
[["regid1","regid2","regid3","regid4"],"regid5"]
Its a major headache
You already get an array when you decode it:
// decode json
$decoded_json= json_decode($current_regids);
// now you have an array or object, depending on the input
// in your case it seems to be an array
And then you put the result in another array:
//save to php format array
$array = array($decoded_json);
So now you have a nested array.
You need to remove this line / use $decoded_json as the array you want to manipulate:
$array = array($decoded_json);
Note:- If you use array_push() to add one element to the array it's better to use $array[] = "value" because in that way there is no overhead of calling a function and it is also much faster and safer than array_push().
This question already has answers here:
PHP function to build query string from array
(4 answers)
Closed 7 months ago.
I have an array of data comes from $_POST and I want to send them by curl to another page.
curl_setopt($s,CURLOPT_POST,true);
curl_setopt($s,CURLOPT_POSTFIELDS,$this->_postFields);
$this->_postFields must be an string like a=2&b=t right?
so if I want to send array of data with curl to another page I must turn array to query string right?
How should I do it with PHP?
♦I tried serialize() and unserialize() but thier format is not same as query string right?
so what should I do? (I need something like .serialize() in jQuery that work on array not FORM)
♦ And the destination path is not under my control and the $_POST in the destination should be as $_POST not as its base64 encoded so I can't use such codes.
$array = array(1,2,3);
$encoded = json_encode($array);
$decoded = json_decode($encoded);
print_r($decoded);
Any Ideas?
thanks in advance.
You can use http_build_query:
curl_setopt($s, CURLOPT_POSTFIELDS, http_build_query($this->_postFields));
NOTICE
It looks beauty, but to use this approach be careful about url encoding .Look next:
$_POST["some value"]='value1'; // " " between
$_POST["next value"]='value2'; // " " between
$url = http_build_query($_POST);
echo $url;
// OUTPUT
some+value=value1&next+value=value2
Of course, after sending this $url we will not get expected variables from $_POST.
I think you can just do this:
curl_setopt($s, CURLOPT_POSTFIELDS, http_build_query($this->_postFields));
If I understand, you can use json.
$array = array(1,2,3);
$encoded = json_encode($array);
$decoded = json_decode($encoded);
print_r($decoded); //Look to it
If is not it, can be it:
$array = array(1,2,3);
echo http_build_query($array); //Look to it