I have this function in php
<?php function showTable(){
$url = "http://10.0.0.1/lib/api/desk/branch/";
$params = array ("action" => "list","company_key" => "1");
$result=requestURL($url,$params);
$json_a=json_decode(strip_tags($result),true);
?>
This is the json I got from the code above. I need to check the key "status". If it has a value "no", it should display an alert that status is not ok. Thanks!
{
"init": [
{
"status": "ok",
"record_count": 9,
"code": "",
"message": "",
"page_count": null,
"current_page": 0
}
]
}
Easy.
Suppose you hold the JSON in $json.
$jsonDecoded = json_decode($json, true);
if($jsonDecoded['init'][0]['status'] != 'ok') {
print "status is not ok :(";
}
Let say that json is in $json variable
$json = json_decode($json,true);
$status = $json['init'][0]['status'];
if($status=='ok'){
# do something here
}else{
# display not ok here
}
Related
I have a .json file and I want to append an object to a vector in the file, but I got some errors.
$json = file_get_contents('materialsdb/'.$_POST["materialtype"].'.json');
$jsonarray = json_decode($json, true);
$myObj->short = $_POST["short"];
//here I got: Warning: Creating default object from empty value
$myObj->title = $_POST["title"];
$myObj->description = $_POST["description"];
$myObj->cover = "";
$myObj->VR = false;
$myObj->slow = false;
$td = '2D';
$myObj->$td = false;
$fd = '3D';
$myObj->$fd = false;
if($_POST["isprivate"]){
$myObj->license = "nonfree";
} else {
$myObj->license = "free";
}
$myObj->lang = "en";
$id = count($jsonarray['packages'])+1;
$myObj->id = $id;
$myObj->soon = false;
$myObj->date = $_POST["date"];
$myObj->creator = $_POST["creator"];
$myObj->creator_institution = $_POST["creator_institution"];
$myObj->keywords = $_POST["keywords"];
$myObj->data = $_POST["data"];
$myJSON = json_encode($myObj);
echo $myJSON;
array_push($myJSON,$jsonarray['packages']);
//here I got: Warning: array_push() expects parameter 1 to be array, string given
$jsondata = json_encode($jsonarray, true);
$myFile = 'materialsdb/'.$_POST["materialtype"].'.json';
if(file_put_contents($myFile, $jsondata)) {
echo 'Data successfully saved';
} else
echo "error";
And when I try to save it then It is saved, but without the modifications, without the new object, but where I echo $myJSON there the object seems good.
Here is an example of my .json file:
{
"description": "some description",
"creators": [
{
"name": "cname",
"whoishe": "cv",
"avatar": "",
"id": 123
}
],
"lang": "en",
"materialname": "mat name",
"generalmaterialid": "mat_id",
"thismaterialid": "this_mat_id",
"packages": [
{
"short": "pack short desc",
"title": "pack title",
"description": "pack long desc",
"cover": "pack cover",
"VR": true,
"slow": true,
"2D": true,
"3D": true,
"license": "free",
"lang": "en",
"id": 1,
"soon": false
}
]
}
I have been inspired from here: https://www.w3schools.com/js/js_json_php.asp and here http://www.kodecrash.com/javascript/read-write-json-file-using-php/.
What have I done wrong here? How can I resolve it? What is the correct version in this case? Thanks for any help!
Firstly, you've got your arguments to array_push() back to front. The array you want to insert into has to be the first argument you give to the function.
Secondly, you're appending a JSON string ($myJSON) to the array, instead of your object data. This doesn't work because when you later come to encode the whole array as JSON, the bit that's already a JSON string is simply treated as a string, and ends up being double-encoded. You need to push the actual PHP object to the array. It will be encoded later when everything else is.
So
$myJSON = json_encode($myObj);
echo $myJSON;
array_push($myJSON,$jsonarray['packages']);
can become simply
array_push($jsonarray['packages'], $myObj);
P.S. You can also remove the warning about "Creating default object from empty value" by writing
$myObj = new \stdClass();
just before the line
$myObj->short = $_POST["short"];
so that you're adding your properties to an object which already exists.
This is my JSON result:
{
"#odata.context": "http://wabi-west-europe-redirect.analysis.windows.net/v1.0/collections/washington/workspaces/37380bc1-dd47-4c95-8dbd-5efecafc8b26/$metadata#reports",
"value": [
{
"id": "6ea77895-f92a-4ca6-90f7-cdade3683cd6",
"modelId": 0,
"name": "america",
"webUrl": "https://app.powerbi.com/reports/6ea77895-f92a-4ca6-90f7-cdade3683cd6",
"embedUrl": "https://embedded.powerbi.com/appTokenReportEmbed?reportId=6ea77895-f92a-4ca6-90f7-cdade3683cd6",
"isOwnedByMe": true,
"isOriginalPbixReport": false,
"datasetId": "3f1f480c-4a8c-4756-87eb-fc29f5d76de3"
},
{
"id": "ce558be6-aaf9-4bee-b344-6db7754e572b",
"modelId": 0,
"name": "dency",
"webUrl": "https://app.powerbi.com/reports/ce558be6-aaf9-4bee-b344-6db7754e572b",
"embedUrl": "https://embedded.powerbi.com/appTokenReportEmbed?reportId=ce558be6-aaf9-4bee-b344-6db7754e572b",
"isOwnedByMe": true,
"isOriginalPbixReport": false,
"datasetId": "5264cf84-214a-4c33-8f8e-f421d8ce1846"
}
]
}
In PHP im getting into
$response = json_decode($aboveresult);
But My problem is the value is in array.I want to get both the array value like id,modelId,Name,...
Please help me.
I tried $response['value'].But its showing error like Cannot use object of type stdClass as array
json_decode() accepts a second parameter, which is by default false. If you pass true, the function will return you an associative array instead of an instance of stdClass and you can work with it the way you tried before.
You have to change:
$response = json_decode($aboveresult,true);
When you mentioned the second parameter as true you will get the ASSOCIATIVE array
Try this
echo "<pre>";
$json_data = json_decode($json); //$json = your json string
print_r($json_data->value);
foreach($json_data->value as $value) {
echo 'ID: '.$value->id .'<br>';
echo 'modelId: '.$value->modelId .'<br>';
echo 'name: '.$value->name .'<br>';
}
I want to adding array's to an existing .json file with with a HTML form.
this is my PHP:
$myFile = "data.json";
$newArray = array(
'name'=> $_POST['name'],
'date'=> $_POST['date']
);
$fileTmp = file_get_contents($myFile);
$tempArray = json_decode($fileTmp);
array_push($tempArray, $newArray);
$jsonData = json_encode($tempArray);
file_put_contents($myFile, $jsonData);
this is my JSON:
[
{
"name": "name 1",
"date": "01.02.2017"
},
{
"name": "name 2",
"date": "05.02.2017"
},
{
"name": "name 3",
"date": "05.03.2017"
}
]
The problem is i got the warning
"array_push() expects parameter 1 to be array, null given in..."
and in the JSON there's is only null. What is my problem with my code?
Add a second parameter to json_decode() and set it to true:-
$tempArray = json_decode($fileTmp,true);
array_push($tempArray, $newArray);
Apart from using the associative version of json_decode as already stated in the other answer, I think that the problem is your input json file.
You should check for valid content and create your default array if the json is empty:
$fileTmp = file_get_contents($myFile);
$tempArray = json_decode($fileTmp, true);
if (!$tempArray) {
$tempArray = array();
}
...
I complied code, it works. Check permissions for data.json file.
I try to read IME field in PHP from following JSON FORMAT:
{"komentarji": [ {"RC_KOMENTARJI": [ {
"K_ID": 101,
"STATUS": "A",
"IME": "boris",
"E_MAIL": "test#example.com",
"KOMENTAR": "testni vnos",
"IP": "10.0.0.6",
"DATUM_ZAPISA": "2016-12-03T23:23:47Z",
"DATUM_UREJANJA": "2016-12-03T23:24:01Z"
},
{
"K_ID": 1,
"STATUS": "A",
"IME": "Peter",
"KOMENTAR": "Zelo profesionalno ste opravili svoje delo.",
"IP": "10.0.0.8",
"DATUM_ZAPISA": "2011-05-04T00:00:00Z"
}
] } ] }
How can I reach that field via foreach in PHP? Thank you.
Let you decode the json to object named $result.
If you want to read first IME then try this
$result->komentarji[0]->RC_KOMENTARJI[0]->IME
If you want to read all IME then you have to apply loop throw komentarji and RC_KOMENTARJI
Decode it by using json_decode().
$object = json_decode($json);
// result in object
$array = json_decode($json, true);
// result in array
You can try this:
$array = json_decode($json, true);
foreach ($array['komentarji'] as $key => $value) {
foreach ($value['RC_KOMENTARJI'] as $k => $val) {
echo $val['IME'] . "<br/>";
}
}
This will print:
boris
Peter
Hope it helps!!!
I have a URL that returns a JSON object like this:
[
{
"idIMDB": "tt0111161",
"ranking": 1,
"rating": "9.2",
"title": "The Shawshank Redemption",
"urlPoster": "http:\/\/ia.media-imdb.com\/images\/M\/MV5BODU4MjU4NjIwNl5BMl5BanBnXkFtZTgwMDU2MjEyMDE#._V1_UX34_CR0,0,34,50_AL_.jpg",
"year": "1994"
}
]
URL : http://www.myapifilms.com/imdb/top
I want to get all of the urlPoster value and set in a array's element, and convert array to JSON so echo it.
How can I do it through PHP?
You can do something like that :
<?php
$json_url = "http://www.myapifilms.com/imdb/top";
$json = file_get_contents($json_url);
$data = json_decode($json, TRUE);
echo "<pre>";
print_r($data);
echo "</pre>";
?>
$json = file_get_contents('http://www.myapifilms.com/imdb/top');
$array = json_decode($json);
$urlPoster=array();
foreach ($array as $value) {
$urlPoster[]=$value->urlPoster;
}
print_r($urlPoster);
You can simply decode the json and then pick whatever you need:
<?php
$input = '[
{
"idIMDB": "tt0111161",
"ranking": 1,
"rating": "9.2",
"title": "The Shawshank Redemption",
"urlPoster": "http:\/\/ia.media-imdb.com\/images\/M\/MV5BODU4MjU4NjIwNl5BMl5BanBnXkFtZTgwMDU2MjEyMDE#._V1_UX34_CR0,0,34,50_AL_.jpg",
"year": "1994"
}
]';
$content = json_decode($input);
$urlPoster = $content[0]->urlPoster;
echo $urlPoster;
The output obviously is the URL stored in that property:
http://ia.media-imdb.com/images/M/MV5BODU4MjU4NjIwNl5BMl5BanBnXkFtZTgwMDU2MjEyMDE#._V1_UX34_CR0,0,34,50_AL_.jpg
BTW: "The Shawshank Redemption" is one of the best films ever made...
This how you do the same thing with array_map function.
<?php
#function to process the input
function process_input($data)
{
return $data->urlPoster;
}
#input url
$url = 'http://www.myapifilms.com/imdb/top';
#get the data
$json = file_get_contents($url);
#convert to php array
$php_array = json_decode($json);
#process the data and get output
$output = array_map("process_input", $php_array);
#convert the output to json array and print it
echo json_encode($output);