PHP code to READ JSON - php

I'm looking for a php code to read the JSON object (which I'm going to upload using Android into the url) and I also want the php function to insert the data into my db. Can someone please help me?
This is my JSON object
{
"id": "mID",
"description": "des",
"stars": "mStars",
"name": "avatar",
"year": "mYear",
"rating": "mRating",
"director": "mDirector"
"url": "www.dummy.com"
}
this is my php code
$app->post(
'/post/',
function () use ($app){
echo 'This is a POST route';
$json = $app->request->getBody();
$data = json_decode($json, true);
echo $data['name'];
echo $data['id'];
echo $data['description'];
echo $data['stars'];
echo $data['rating'];
echo $data['director'];
echo $data['url'];
echo $data['year'];
createMovie($data);
}
);
The following code is in a separate file. I have similar files with select statements which are working perfectly fine.
<?php
function createMovie($data) {
$conn=getDB();
if($stmt=$conn->prepare("$sql="INSERT INTO Movies (id, name,description, director, year, rating, stars, url)
VALUES ($data['id'],$data['name'],$data['description'],$data['director'],$data['year'],$data['rating'],$data['stars'],$data['url'])";
{
$stmt->execute();
$conn->close();
}
}
?>
when I type www.example.com/post/ I'm getting Error 404 not found

Use json_decode() like so:
<?php
$jsonData = '{ "user":"John", "age":22, "country":"United States" }';
$phpArray = json_decode($jsonData);
print_r($phpArray);
foreach ($phpArray as $key => $value) {
echo "<p>$key | $value</p>";
}
?>
Here is the link to the official documentation of the function.

Related

Decoding JSON SubArray PHP

I have looked around on Google for quite some time now, and I'm unable to find a solution that works for me.
I have this JSON Array:
[
{
"id": 1000,
"userIdent": "ABC1000",
"username": "john.doe",
"contacts": [
{
"id": 2000,
"clientId": 1000,
"email": "john.doe#example.com",
"phone": "",
"name": "",
"isBilling": false,
"isContact": false,
"types": [
{
"id": 3000,
"name": "Home contact"
}
]
}
]
}
]
and I have this PHP code:
$json = json_decode($response, true);
foreach($json as $item) {
echo $item['id'] . "<br>";
echo $item['userIdent'] . "<br>";
echo $item['contacts']['phone'] . "<br><br>";
foreach($json->contacts as $contacts) {
echo $contacts->phone;
echo $contacts['contacts']['phone'];
}
}
I have tried:
$item['contacts']['phone'];
$contacts->phone;
$contacts['contacts']['phone'];
I can't seem to be able to full any of the data from the sub-array "contacts". Any help would be greatly appreciated!
Note:- When you use true while using json_decode() it converts all json data to array(inner or outer). So you need to treat contacts as an array not an object.
So You need to iterate over $item['contacts'] array in the second foreach()
Do like below:-
$json = json_decode($response, true);
foreach($json as $item) {
echo $item['id'] . "<br>";
echo $item['userIdent'] . "<br>";
foreach($item['contacts'] as $contacts) {//treat contacts as an array not as an object
echo $contacts['phone'];
}
}
Output:- https://eval.in/952121 (i have taken phone number for testing purpose)
You have made a mistake, on your json, the contacts property is an array, so you can't access it (either in javascript or php) as an object with $contacts->contacts['phone'].
You should do something like that : $contacts->contacts[0]['phone'] or iterate other each contacts if there may be many.
Your code should look more like this
foreach($json as $item) { // 1
echo $item['id'] . "<br>";
echo $item['userIdent'] . "<br>";
foreach($item['contacts'] as $contact) { // 2
echo $contact['phone'];
}
}
So in the first foreach you start iterating over you entire array of items (1). Inside an item is an array contacts, so you start iterating over that with a new foreach (2). Each contact can be accessed directly inside the inner foreach.
Also, on decoding you said you wanted an array as output, so you should expect that and always access it like an array (square braces). If you would have gone for an object, the $contacts->phone syntax would work, but you shouldn't mix them like you are doing.
I hope this makes sense. Feel free to ask if not.

Php loop with json coming back empty

what am i doing wrong here?
when i have only One result coming back this code works perfectly
$someObject = json_decode($data);
$id=$someObject->clips[0]->id;
but when i want to do a loop because i may get back 10 results this code is not working, i am sure i am missing something very simple here
$someObject = json_decode($data);
//var_dump($someObject);
foreach($someObject as $json){
echo $json->clips[0]->id;
}
EDIT:
this solution worked for anyone else who comes looking
foreach ($someObject->clips as $clip){
echo $clip->id. "<br>";
}
not sure how the other one answers the for loop issue i was having however.
You need to change this index [0] to dynamic index.
foreach($someObject as $k => $json){
echo $json->clips[$k]->id; // Insert $k here
}
change this
foreach($someObject as $json){
echo $json->clips[0]->id;
}
to
$i=0;
foreach($someObject as $json){
echo $json->clips[$i]->id;
$i++;
}
or as miken32 stated in the comment
foreach ($someObject->clips as $clip){
echo $clip->id;
}
read this reference: control-structures.foreach.php
in php array if you want to get all of items iterate you can use foreach
imaging you have this sample json:
{
"clips": [{
"id": 1,
"name": "test",
"tags": [
"tag1",
"tag2",
"tag3"
]
},
{
"id": 2,
"name": "test2",
"tags": [
"tag4",
"tag5",
"tag6"
]
}
]
}
if you want to get clips and tag list you can use this code:
<?php
$jsonText = '{"clips": [{"id": 1,"name": "test","tags": ["tag1","tag2","tag3"]},{"id": 2,"name": "test2","tags": ["tag4","tag5","tag6"]}]}';
$jsonObj = json_decode($jsonText);
// in this loop you can get clipObject
foreach($jsonObj->clips as $clipObj){
echo "clip id:" . $clipObj->id . "<br>\n";
echo "clip name:" . $clipObj->name. "<br>\n";
// in this loop you can get tags
foreach($clipObj->tags as $tag){
echo "clip tag:" . $tag. "<br>\n";
}
}

Parsing JSON in PHP to extract lat/lon

I need to parse this JSON using PHP
[{
"options": {
"allowUTurn": false
},
"latLng": {
"lat": 44.91138,
"lng": 7.671783
},
"name": "Corso Vinovo, Carignano, TO, Piemont, Italy",
"_initHooksCalled": true
}, {
"options": {
"allowUTurn": false
},
"latLng": {
"lat": 44.909979,
"lng": 7.676234
},
"name": "Il Tempio del Pane, Corso Cesare Battisti, Carignano, TO, Piemont, Italy",
"_initHooksCalled": true
}, {
"options": {
"allowUTurn": false
},
"latLng": {
"lat": 44.907805,
"lng": 7.674952
},
"name": "Banca Intesa, Via Ferdinando Salotto, Carignano, TO, Piemont, Italy",
"_initHooksCalled": true
}]
to extract the coordinates in lat / lon.
What have I to use after
echo $wayPoints->?????
and how I create a for cicle to extract all the coordinates?
Any help will be appreciated!!Thank you!
Cesare
EDIT: a code sample (note that the JSON come from a POST parameter ...)
<?php
echo "Waypoints ...</br>";
echo "</br>";
echo $_POST['wayPoints'];
$wayPoints = $_POST['wayPoints'];
$json = json_decode($wayPoints);
foreach($json as $f){
echo $f['latLng']['lat'];
echo $f['latLng']['lng'];
}
?>
so should be more clear ... (the code NOT working ...)
Thank you again ...
EDIT 2: this code work !!!
<?php
echo "Waypoints ...</br>";
echo "</br>";
echo $_POST['wayPoints'];
$wayPoints = $_POST['wayPoints'];
$json = json_decode($wayPoints, true);
foreach($json as $f){
echo "</br>";
echo $f['latLng']['lat'];
echo "</br>";
echo $f['latLng']['lng'];
echo "</br>"; }
?>
the output is
44.91138
7.671783
44.909979
7.676234
44.907805
7.674952
Thank you all!
This will convert your json object into an associative array, then iterate with foreach.
//use json_decode in associative mode
$decoded = json_decode($json, true);
//Your object is now an array called $decoded
//Your locations are subarrays of $decoded
//The co-ords are subarrays of each $locationArray
foreach($decoded as $locationArray)
{
echo "The co-ordinates for {$locationArray['name']} are: {$locationArray['latLng']['lat']},{$locationArray['latLng']['lng']}" . PHP_EOL;
}
First you need to do $file = json_decode()
and then the file you get just add to foreach:
foreach($file as $f){
echo $f['latLng']['lat'];
echo $f['latLng']['lng'];
}

Getting multiple keys' values from JSON with PHP

I am trying to extract team names, players name from this json. but get no resul.
My json file looks like. any idea where I am wrong ?
{"items":[
{"_id":305501,"id":"305501","created_at":"2015-10-19T19:57:02+13:00","updated_at":"2015-10-19T21:34:50+13:00","name":"Match in progress","verification_level":0,
"club_one":{"name":"Degree Club","id":14748,
"team":{"name":"Degree College XI","id":13009,"avatar":"/original/team/default_thumb.png",
"players":[
{"id":null,"name":"D Vinaya"},
{"id":617744,"name":"V Avika"},
{"id":617745,"name":"C Rumes"},
{"id":1360372,"name":"R Ferdo"}
],
"innings":[{"overs":34,"over_balls":0,"runs":99,"wickets":7}]
}
},
"club_two":{"name":"George Club","id":147736,
"team":{"name":"George College XI","id":154503,"avatar":"/original/team/default_thumb.png",
"players":[
{"id":null,"name":"M Premathe†"},
{"id":null,"name":"S Tion"},
{"id":null,"name":"N Perra"},
{"id":1400317,"name":"S Ren"}
],
"innings":[]
}
},
"processed":true,"visible":true,"match_level":{"name":null,"id":null}
}
],
"meta":{"total_pages":1}
}
and here is the php code.
$json_file = json_decode($load_json);
foreach ($items as $item) {
echo $item->$json_file->_id;
echo $item->$json_file->club_one;
echo $item->$json_file->club_two;
}
You are doing it wrong. As far as your json is concerned, loop it like this
$json_file = json_decode($json);
foreach ($json_file->items as $item) {
echo $item->id;
echo $item->club_one->name;
echo $item->club_two->name;
}

Get JSON from URL by PHP

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);

Categories