Sekarang pertukaran data baik itu dekstop, mobile, web sangat mudah dilakukan dengan adanya JSON. Banyak API yang menyediakan dengan format JSON, seperti api.tiket.com, api.cekresi.com bahkan perusahaan besar semacam facebook, google, twitter juga menggunakan API.
Cangkal kali ini mencoba sharing bagaimana mengambil data JSON dari URL (website) menggunakan framework codeigniter. URL yang digunakan yaitu http://jsonplaceholder.typicode.com/posts/ . URL ini memang sengaja dibuat untuk digunakan sebagai testing. Data JSON yang diberi oleh URL tadi bentuknya seperti ini
[{ "userId": 1, "id": 1, "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit", "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto" }, { "userId": 1, "id": 2, "title": "qui est esse", "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla" }, { "userId": 1, "id": 3, "title": "ea molestias quasi exercitationem repellat qui ipsa sit aut", "body": "et iusto sed quo iure\nvoluptatem occaecati omnis eligendi aut ad\nvoluptatem doloribus vel accusantium quis pariatur\nmolestiae porro eius odio et labore et velit aut" }, { "userId": 1, "id": 4, "title": "eum et est occaecati", "body": "ullam et saepe reiciendis voluptatem adipisci\nsit amet autem assumenda provident rerum culpa\nquis hic commodi nesciunt rem tenetur doloremque ipsam iure\nquis sunt voluptatem rerum illo velit" }, { "userId": 1, "id": 5, "title": "nesciunt quas odio", "body": "repudiandae veniam quaerat sunt sed\nalias aut fugiat sit autem sed est\nvoluptatem omnis possimus esse voluptatibus quis\nest aut tenetur dolor neque" }, ..... { "userId": 10, "id": 100, "title": "at nam consequatur ea labore ea harum", "body": "cupiditate quo est a modi nesciunt soluta\nipsa voluptas error itaque dicta in\nautem qui minus magnam et distinctio eum\naccusamus ratione error aut" }]ok langsung saja kita coba coding
pertama kita tulis code dibawah ini pada controller Json
public function index() { $url="http://jsonplaceholder.typicode.com/posts/"; $get_url = file_get_contents($url); $data = json_decode($get_url); $data_array = array( 'datalist' => $data ); $this->load->view('json/json_list',$data_array); }
penjelasan dari baris function index yaitu
variable $url adalah nama atau alamat url yang menyediakan data JSON
variable $get_url adalah function php untuk mengambil konten dari url yaitu file_get_contents
setelah data diambil lalu
variable $data berfungsi sebagai merubah data json dalam bentuk object PHP, kalo mau tau bentuknya seperti apa
tambahkan code print_r $data; dibawah baris $data = json_decode($get_url);
hasilnya akan seperti ini
Array ( [0] => stdClass Object ( [userId] => 1 [id] => 1 [title] => sunt aut facere repellat provident occaecati excepturi optio reprehenderit [body] => quia et suscipit suscipit recusandae consequuntur expedita et cum reprehenderit molestiae ut ut quas totam nostrum rerum est autem sunt rem eveniet architecto ) [1] => stdClass Object ( [userId] => 1 [id] => 2 [title] => qui est esse [body] => est rerum tempore vitae sequi sint nihil reprehenderit dolor beatae ea dolores neque fugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis qui aperiam non debitis possimus qui neque nisi nulla ) [2] => stdClass Object ( [userId] => 1 [id] => 3 [title] => ea molestias quasi exercitationem repellat qui ipsa sit aut [body] => et iusto sed quo iure voluptatem occaecati omnis eligendi aut ad voluptatem doloribus vel accusantium quis pariatur molestiae porro eius odio et labore et velit aut ) [3] => stdClass Object ( [userId] => 1 [id] => 4 [title] => eum et est occaecati [body] => ullam et saepe reiciendis voluptatem adipisci sit amet autem assumenda provident rerum culpa quis hic commodi nesciunt rem tenetur doloremque ipsam iure quis sunt voluptatem rerum illo velit ) [4] => stdClass Object ( [userId] => 1 [id] => 5 [title] => nesciunt quas odio [body] => repudiandae veniam quaerat sunt sed alias aut fugiat sit autem sed est voluptatem omnis possimus esse voluptatibus quis est aut tenetur dolor neque ) [5] => stdClass Object ( [userId] => 1 [id] => 6 [title] => dolorem eum magni eos aperiam quia [body] => ut aspernatur corporis harum nihil quis provident sequi mollitia nobis aliquid molestiae perspiciatis et ea nemo ab reprehenderit accusantium quas voluptate dolores velit et doloremque molestiae ) ............ [99] => stdClass Object ( [userId] => 10 [id] => 100 [title] => at nam consequatur ea labore ea harum [body] => cupiditate quo est a modi nesciunt soluta ipsa voluptas error itaque dicta in autem qui minus magnam et distinctio eum accusamus ratione error aut ) )lalu
variable $data_array merubah object dalam bentuk array
dan yang terakhir $this->load->view('json/json_list',$data_array); yaitu menampilkan data dari variable $data_array ke View CI
kemudian untuk menampilkan data di view CI, tulis kode seperti ini
<?php
$start = 0;
foreach ($datalist as $value)
{
?>
<tr>
<td><?php echo ++$start ?></td>
<td><?php echo $value->userId;?></td>
<td><?php echo $value->id; ?></td>
<td><?php echo $value->title; ?></td>
<td><?php echo $value->body; ?></td>
</tr>
<?php
}
?>
ok sobat cangkal, coba di browser apakah hasilnya sama seperti gambar di bawah ini? apabila iya berarti sobat sudah berhasil menampilkan data JSON menggunakan framework codeigniter.
codeigniter ~ Json decode |
apabila mengalami kesulitan bisa coba langsung source code di download di sini
regards,
cangkal
alhamdulillah ini tutorial yang ane cari
BalasHapusizin sedot gan.
langsung sobat, semoga bermanfaat
Hapuskalau misal yang mau ditampilin userId 1 aja gimana gan caranya?
BalasHapusBisa dengan cara dikondisikan seperti ini sob
Hapusforeach($datalist as $value) [
if($value->userId == '1') {
print_r($value->userId);
}
}
tanpa foreach gimana bro? soalnya data saya 1, jadi error, kalau pakai database biasa saya biasanya pakai row bukan result_array ataupun array
BalasHapuslangsung echo saja mba bro
Hapus$json = '{
"title": "JavaScript: The Definitive Guide",
"author": "David Flanagan",
"edition": 6
}';
$book = json_decode($json);
// access title of $book object
echo $book->title;
Did you hear there's a 12 word sentence you can say to your partner... that will induce intense feelings of love and instinctual attraction to you deep inside his chest?
BalasHapusBecause deep inside these 12 words is a "secret signal" that triggers a man's instinct to love, adore and protect you with all his heart...
12 Words Will Fuel A Man's Love Response
This instinct is so hardwired into a man's mind that it will drive him to try harder than ever before to do his best at looking after your relationship.
Matter-of-fact, triggering this dominant instinct is absolutely mandatory to achieving the best ever relationship with your man that the moment you send your man one of the "Secret Signals"...
...You will instantly notice him open his heart and soul for you in a way he haven't expressed before and he will identify you as the only woman in the galaxy who has ever truly attracted him.
This is how my partner Wesley Virgin's adventure starts in this SHOCKING AND CONTROVERSIAL video.
BalasHapusYou see, Wesley was in the army-and shortly after leaving-he revealed hidden, "mind control" secrets that the government and others used to obtain whatever they want.
As it turns out, these are the same SECRETS tons of celebrities (notably those who "come out of nowhere") and top business people used to become rich and successful.
You probably know how you only use 10% of your brain.
Really, that's because the majority of your brain's power is UNCONSCIOUS.
Maybe this conversation has even occurred INSIDE your very own mind... as it did in my good friend Wesley Virgin's mind 7 years ago, while driving an unlicensed, garbage bucket of a car with a suspended driver's license and on his banking card.
"I'm so fed up with going through life check to check! When will I become successful?"
You've been a part of those those types of conversations, ain't it right?
Your own success story is waiting to start. Go and take a leap of faith in YOURSELF.
Take Action Now!
Do this hack to drop 2lb of fat in 8 hours
BalasHapusAt least 160,000 women and men are trying a simple and secret "liquids hack" to drop 2lbs every night as they sleep.
It is painless and works with everybody.
This is how to do it yourself:
1) Go get a glass and fill it up half the way
2) And now follow this awesome HACK
you'll be 2lbs lighter the next day!
This is how my partner Wesley Virgin's adventure starts in this SHOCKING AND CONTROVERSIAL video.
BalasHapusWesley was in the military-and soon after leaving-he unveiled hidden, "SELF MIND CONTROL" tactics that the CIA and others used to get everything they want.
These are the exact same tactics many celebrities (notably those who "come out of nothing") and the greatest business people used to become rich and famous.
You probably know how you utilize only 10% of your brain.
That's mostly because the majority of your BRAINPOWER is UNCONSCIOUS.
Perhaps that conversation has even taken place INSIDE your own brain... as it did in my good friend Wesley Virgin's brain 7 years back, while driving a non-registered, beat-up garbage bucket of a car without a driver's license and $3 in his pocket.
"I'm so fed up with going through life paycheck to paycheck! Why can't I turn myself successful?"
You've been a part of those those types of thoughts, ain't it right?
Your very own success story is waiting to be written. You need to start believing in YOURSELF.
Take Action Now!