Showing posts with label JSON. Show all posts
Showing posts with label JSON. Show all posts

Thursday, 20 June 2024

Creating a basic authentication API using Laravel 11

I have used this blog post to create the API, but with a couple of tweaks and some additional explanations. So, thanks Hendrik!

Pre-requisites

I'll assume that you have Laravel set up to use laravel commands.

First, create your application

Run:
laravel new sanctum-example

To question 'Would you like to install a starter kit?', select 'No starter kit'.
To question 'Which testing framework do you prefer?',  select 'Pest'.
To question 'Would you like to initialize a Git repository?', select 'yes'.
To question 'Which database will your application use?', select 'MySQL'.
To question 'Would you like to run the default database migrations?', select 'no'.

Run:
cd sanctum-example

Run:
php artisan install:api

At this stage, the API script reports: "INFO  API scaffolding installed. Please add the [Laravel\Sanctum\HasApiTokens] trait to your User model".
So, let's do that first.
Open app/Models/User.php and change the line:
use HasFactory, Notifiable;
to:
use HasApiTokens, HasFactory, Notifiable;
This will also require you to add the namespace:
use Laravel\Sanctum\HasApiTokens;

Now that's done:
Delete the resources directory
Delete the file routes/web.php
Delete the line web: __DIR__.'/../routes/web.php', from bootstrap/app.php

At this stage I like to create the database so that migrations can be added.
Run:
php artisan serve
Now open your favourite MySQL editor and create the database, i.e.
CREATE DATABASE `sanctum-example`;
Now we can close the server using Ctrl-c.
We should now edit our database settings in the .env file to something similar to this:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=sanctum-example
DB_USERNAME=root
DB_PASSWORD=<yourpassword>


We're now in a good place to do our migrations:
php artisan migrate

At this stage Sanctum doesn't have a configuration published. For this we have to run:
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"

Create an Authentication Controller

Our application is API only, so we don't need to create a separate directory to hold API code. So, run:
php artisan make:controller AuthController
We should now have a file called app/Http/Controllers/AuthController.php
To this controller, let's add a method to handle registration:
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
    'name'      => 'required|string|max:255',
    'email'     => 'required|string|max:255|unique:users',
    'password'  => 'required|string'
]);

if ($validator->fails()) {
    return response()->json($validator->errors());
}

$user = User::create([
    'name'      => $request->name,
    'email'     => $request->email,
    'password'  => Hash::make($request->password)
]);

$token = $user->createToken('auth_token')->plainTextToken;
return response()->json([
    'data'          => $user,
    'access_token'  => $token,
    'token_type'    => 'Bearer'
]);
}
A method to handle login:
public function login(Request $request)
{
        $validator = Validator::make($request->all(), [
            'email'     => 'required|string|max:255',
            'password'  => 'required|string'
        ]);
        if ($validator->fails()) {
            return response()->json($validator->errors());
        }

        $credentials    =   $request->only('email', 'password');

        if (!Auth::attempt($credentials)) {
            return response()->json([
                'message' => 'User not found'
            ], 401);
        }

        $user   = User::where('email', $request->email)->firstOrFail();
        $token  = $user->createToken('auth_token')->plainTextToken;

        return response()->json([
            'message'       => 'Login success',
            'access_token'  => $token,
            'token_type'    => 'Bearer'
        ]);
}
Finally, a method to handle logout:
public function logout()
{
        Auth::user()->tokens()->delete();
        return response()->json([
            'message' => 'Logout successfull'
        ]);
}
In order to support these methods, you need to have the following namespaces at the top of your class:
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;

Create Routes

Next we need to edit the file  routes/api.php
We'll begin by adding our new namespace to the top of the file:
use App\Http\Controllers\AuthController;

Now we can add the routes to support the work we did in the AuthController.
A route for /user should already exist. Don't remove/override that, we'll need it later. Add:
Route::post('/register', [AuthController::class, 'register']);
Route::post('/login', [AuthController::class, 'login']);

Route::middleware('auth:sanctum')->group(function () {
    Route::post('/logout', [AuthController::class, 'logout']);
});

Testing our work

Let's start the server again:
php artisan serve
I use Postman for this, but essentially, below are the values you need to perform in each test.

Register

Method: POST
URL: http://127.0.0.1:8000/api/register
Header fields: Accept: application/json
Body fields: name,email,password
Make up your own name, email address and password

Login

Method: POST
URL: http://127.0.0.1:8000/api/login
Headers fields: Accept: application/json
Body fields: email, password

Get User

Method: GET
URL: http://127.0.0.1:8000/api/login
Headers: Accept : application/json
Authorization: <Bearer token>
Make use of the token returned when you used the login or register API.

Logout

Method: POST
URL: http://127.0.0.1:8000/api/logout
Headers: Accept: application/json
Authorization: <Bearer token>
Make use of the token returned when you used the login or register API.

Tuesday, 18 June 2024

Deleting data using the API Resource to a Laravel 11 Model

Pre-requisites

We'll assume 3 things:

  1. That the model was created using the approach in this blog post.
  2. That the route was created using the approach in this blog post.
  3. That a migration file has been set using this blog post.
  4. That an Eloquent API Resource has been set up using this blog post.


Now open the YourController.php.

Develop the function destroy() like this:

public function destroy(YourModel $yourmodel)

{

$yourmodel->delete();

return response()->noContent();

}

To test this in Postman, you'll need to send a DELETE request with the URL of http://localhost/api/yourcontroller/1

In the Headers tab add the key Accept and the value of application/json

In the body select none instead of raw.

Try using an empty object to see if the API returns the validation message.

That should work.

Updating data using the API Resource to a Laravel 11 Model

Pre-requisites

We'll assume 3 things:

  1. That the model was created using the approach in this blog post.
  2. That the route was created using the approach in this blog post.
  3. That a migration file has been set using this blog post.
  4. That an Eloquent API Resource has been set up using this blog post.

Similar to the approach to add data we will update the Http/Requests/UpdateYourRequest.php.
We can begin by removing everything from within the class.
The we will instead extend the class by StoreYourRequest
Now open the YourController.php and remove the edit method.
In the function update() thus:
public function update(UpdateYourRequest $request, YourModel $yourmodel)
{
$yourmodel->update($request->validated());
return YourResource::make($yourmodel);
}
To test this in Postman, you'll need to send a PUT request with the URL of http://localhost/api/yourcontroller/1
In the Headers tab add the key Accept and the value of application/json
In the body select raw and choose the data format JSON.
Try using an empty object to see if the API returns the validation message
Now try an object like this:
{
"name": "My name again"
}
That should work.

Adding data using the API Resource to a Laravel 11 Model

Pre-requisites

We'll assume 3 things:

  1. That the model was created using the approach in this blog post.
  2. That the route was created using the approach in this blog post.
  3. That a migration file has been set using this blog post.
  4. That an Eloquent API Resource has been set up using this blog post.

This exercise will include adding validation of the incoming data.

When we created the model, we selected Form Requests, which created Http/Requests/StoreYourModelRequest.php and Http/Requests/UpdateYourModelRequest.php.

A Form Request in Laravel is a class that encapsulates the validation logic for a form submission. It allows you to separate the validation logic from your controller and makes it easier to reuse the same validation rules across multiple controllers.

We will edit StoreYourModelRequest.

If we're not using authorization the function authorize() should return true.

Now we will validation rules to the name field, thus:

public function rules()

{

return [

'name' => 'required|string|max:255'

];

}

Now in the YourController, we don't need the create method, so delete it. We just need to have a function store() which looks like this:

public function store()

{

$yourmodel = YourModel::create($request->validated())

return YourResource::make($yourmodel);

}


Now in the your model add the attribute

protected $fillable = ['name'];

$fillable is used to prevent unauthorised data manipulation by limiting which attributes can be set on a model.

To test this in Postman, you'll need to send a POST request with the URL of http://localhost/api/yourcontrollername

In the Headers tab add the key Accept and the value of application/json

In the body select raw and choose the data format JSON.

Try using an empty object to see if the API returns the validation message

Now try an object like this:

{

"name": "My name"

}

That should work.

Seeding migrations using factories for a Laravel 11 API Model

Seeding in Laravel is a process that allows you to insert dummy or sample data into a database. 
A factory is a feature that allows you to create fake data for your models, making it easier to test and seed your database with dummy data. Factories are particularly useful for testing, as they provide a way to create predictable and controlled data for your tests.
You'll see below that a factory is set up which describes the type of fake data to be produced during the migration.
Then, in the database seeder, this factory will be called upon for its description, when creating the seeds.

Pre-requisites

We'll assume 3 things:
That the model was created using the approach in this blog post.
That the route was created using the approach in this blog post.
That a migration file has been set using this blog post.

Factory

Now you can open the factory created for your model under database/factories.
This is a good place to add some seed definitions.
In the function definition(), add the field names and the corresponding values to  each field. Here's an example:
public function definition(): array
{
return [
    'name' => $this->faker->name(),
    'description' => $this->faker->sentence(20),
];
}

Seeds

In order to make use of the seed definition you created above, open seeders/DatabaseSeeder.php
public function run(): void
{
YourModel::factory(10)->create();
}

Now in the terminal:
php artisan migrate --seed

Now check in MySQL that the data has been created.
If you followed this blog post the function index(), had some test output of "Hello world" which we tested in Postman. Now we're going to add a listing of the records from our model within our controller and return that as JSON instead. Look for your controller in Http/Controllers/ then edit thus:
public function index()
{
return YourModel::all();
}

Tuesday, 26 February 2019

Vanilla JavaScript Login form POST handler using XHR

I did a similar post to this called Vanilla JavaScript Login form POST handler using fetch. Fetch returns a JavaScript Promise, which can be a bit of a pain so I've also done a version using XHR, see below:

var postJSON = function(url, method, data, callback) {
  var xhr = new XMLHttpRequest();
  xhr.open(method, url, true);
  xhr.responseType = 'json';
  xhr.onload = function() {
    var status = xhr.status;
    if (status === 200) {
      callback(null, xhr.response);
    } else {
      callback(status, xhr.response);
    }
  };
  xhr.send(data);
};

Here's how to call it:
const form = document.querySelector('form');
form.addEventListener('submit', function(ev) {
  ev.preventDefault();
  const url = this.getAttribute('action');
  const method = this.getAttribute('method');

  postJSON(url, method, new FormData(form), function(error, json) {
    if (error !== null) {
      console.log('parsing failed', error);
    } else {
      console.log('json.username', json.username);
      console.log('json.password', json.password);
    }
  });
});

Wednesday, 6 February 2019

Vanilla JavaScript Login form POST handler using fetch

I've been updating my gists lately because I'm now in position to leave jQuery behind. See https://gist.github.com/guitarbeerchocolate
So, here's how to pass login form data to some middleware and accept JSON in return using fetch.

const form = document.querySelector('form');
form.addEventListener('submit', function(ev) {
  ev.preventDefault();
  const url = this.getAttribute('action');
  const method = this.getAttribute('method');

  fetch(url, {
    method: method,
    body: new FormData(form)
  }).then(function(response) {
    return response.json()
  }).then(function(json) {
    console.log('json.username', json.username)
    console.log('json.password', json.password)
  }).catch(function(error) {
    console.log('parsing failed', error)
  })
});

Monday, 14 May 2018

Get blogspot content using JavaScript fetch

This example pulls in JSON data from a blog hosted on blogspot.com

First, I'll need to get fetch.
To add it to your project, change to your project directory:
cd myApp
Then use the following command:
npm install node-fetch --save

const fetch = require('node-fetch');
const url = 'http://some-website.blogspot.com/feeds/posts/default/-/blog?alt=json';
var myFetch = fetch(url);

myFetch.then(response => response.json()).then(function(data) {
  showMyData(data);
}).catch(function(err)
{
  console.log('Caught an error ',err);
});

function showMyData(md) {
  md.feed.entry.forEach((e) => {
    var title = (e.title.$t || '');
var url = (e.link || []).pop().href;
    var date = new Date(e.updated.$t || Date.now());
    var lessLines = e.content.$t.substr(0, 800);
    var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
    var theMonth = months[date.getMonth()];
    var theYear = date.getFullYear();
  });
}

Friday, 11 May 2018

The 2018 Web Developer : JavaScript JSON processing without jQuery

Enter 'fetch'. The JavaScript API which performs HTTP requests.
First, I'll need to get fetch.
To add it to your project, change to your project directory:
cd myApp
Then use the following command:
npm install node-fetch --save

In this example, I have a simple .json file which contains a set of URLs and their types.

const fetch = require('node-fetch');
const url = 'feeds.json';
var myFetch = fetch(url);

myFetch.then(response=>response.json()).then(function(data) {
    showMyData(data);
  });

function showMyData(md)
{
  md.forEach((value) => {
    console.log(value.URL, value.TYPE);
  });
}

Tuesday, 24 April 2018

Live data to your page using EventSource

In the following example I deliver live data to a web page. It's possible to do this quite easily using node.js and socket.io. However most of the websites I create are delivered through a shared server and the providers won't let me install node.js, so here I provide an alternative.
In this instance I use a combination of HTML, JavaScript and PHP. It would also be possible to use jQuery instead of straight JavaScript and PHP with something like python or indeed any other language. I also use a JSON file which could be replaced by any other data source.

Let's begin with data source tester.json
[
{
"name": "Aragorn",
"race": "Human"
},
{
"name": "Gimli",
"race": "Dwarf"
}
]

Now, the HTML file (index.html)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Live data connectivity</title>
</head>
<body>
<table id="myTable">
  <thead>
    <tr>
      <th>Name</th>
      <th>Race</th>
    </tr>
  </thead>
  <tbody></tbody>
</table>
<script src="updatetables.js"></script>
<script src="run.js"></script>
</body>
</html>

Basically we need to check if the HTML table has any data inside. if it doesn't we take data from the data source. If the HTML table does contain data, it will be updated with the contents of the data source. To achieve this we'll use a function inside updatetables.js.
function updateTable(jd, id)
{
  var tbody = document.getElementById(id).tBodies[0];
  for (var i = 0; i < jd.length; i++)
  {
    if(tbody.rows[i] == null)
    {
      /* No data in HTML table */
      var row = tbody.insertRow(i);
      var x = row.insertCell(0);
      x.innerHTML = jd[i].name;
      x = row.insertCell(1);
      x.innerHTML = jd[i].race;
    }
    else
    {
      /* Data in HTML table. Needs updating. */
      var row = tbody.rows[i];
      tbody.rows[i].cells[0].innerHTML = jd[i].name;
      tbody.rows[i].cells[1].innerHTML = jd[i].race;
    }
  }
}

Now that we have a means of updating the table, we need to get the data using stream.php
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$JSON = file_get_contents('tester.json');
echo 'data: '.json_encode($JSON).PHP_EOL.PHP_EOL;
flush();
?>

Finally we can use the JavaScript EventSource object to call stream.php and get our data. Once we have our data, we can pass it to updatetables.js. This is done through run.js
var source = new EventSource('stream.php');
var tableid = 'myTable';
source.onmessage = function(event)
{
  var jsonData = JSON.parse(event.data);
  jsonData = JSON.parse(jsonData);
  updateTable(jsonData, tableid);
};

If you have recreated these files, to test it all works, try changing the values of items in tester.json and see the updates on your page without refresh.




Wednesday, 10 June 2015

Bootstrap formhandler calling class methods with JSON returned and processed

This entry offers a number of techniques through 4 files.

  • index.php contains a message alert which will only be displayed when there is a message to put in it. The forms use an action which contains the name of a class and method which will be used to process the results. There is also a call to custom.js
  • custom.js handles the form submissions and delivers the data returned to the page. It passes the form action and field content to formhandler.php. It receives JSON which then is either passed to a message alert or a data table.
  • formhandler.php receives the call from custom.js. This contains the form action and field content. It takes the form action and uses them to create calls to classes and methods named in the form action. For example and action of myclass/mymethod would be used to create calls similar to those below. The inclusion of the $_POST array allows the form field content to be passed to the class. The data returned is then passed back to custom.js for processing.
$myclass = new myclass($_POST);
$myclass->mymethod;

  • myclassname.class.php contains the example class and methods. The class receives the $_POST array and processes its content. There are 3 methods which demonstrate how to return a string, an array and an object.

This approach is a quick way of utilising many classes. It does not require a .htaccess file to simplify form actions and is flexible in its handling of returned data through JSON.
Have fun.

index.php

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Form handler for many PHP classes using jQuery</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
    <style>
    body
    {
      margin-top:2em;
    }
    #message, #data-table
    {
      display:none;
    }
    </style>
  </head>
  <body>
    <div class="row">
      <div class="container">
        <div class="col-md-12">
          <div id="message" class="alert alert-success" role="alert"></div>
          <!-- <form action="myclassname/myclassmethod_string" method="POST"> -->
          <!-- <form action="myclassname/myclassmethod_array" method="POST"> -->
          <form action="myclassname/myclassmethod_object" method="POST">
            <div class="form-group">
              <label for="name"></label>
              <input type="text" name="name" class="form-control" />
            </div>
            <button type="submit" class="btn btn-default">Submit</button>
          </form>
          <table id="data-table" class="table table-striped">
            <thead>
              <tr>
                <th>Name</th>
                <th>Age</th>
              </tr>
            </thead>
            <tbody>
            </tbody>
          </table>
        </div>
      </div>
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
    <script src="custom.js"></script>
  </body>
</html>

custom.js

(function()
{
  $('form').on('submit', function(event)
  {
    $.post('formhandler.php?action='+$(this).attr('action'), $(this).serialize(), function(data)
    {
      var json_obj = JSON.parse(data);
      if(json_obj.hasOwnProperty('message'))
      {
        $('#message').text(json_obj.message);
        $('#message').show();
        $('#message').fadeOut(3000);
      }
      else
      {
        $.each(json_obj, function(name,age)
        {
          $('#data-table > tbody').appendRow(name,age);            
        });
        $('#data-table').show();
      }
    });
    event.preventDefault();
  });
})();

$.fn.appendRow = function()
{
  var s = '<tr>';
  for (var i = 0; i < arguments.length; i++)
  {
    s += '<td>'+arguments[i]+'</td>';
  }
  s += '</tr>';
  return $(this).append(s);
}

formhandler.php

<?php
if(isset($_GET['action']))
{
$arr = split('/', $_GET['action']);
$class = $arr[0];
$method = $arr[1];
require_once $class.'.class.php';
if(class_exists($class))
{
$evalStr = '$'.$class.' = new '.$class.'($_POST);';
eval($evalStr);
if(method_exists($class, $method))
{
$evalStr = '$returnValue = $'.$class.'->'.$method.'();';
eval($evalStr);
}
else
{
$returnValue = 'Method does not exist';
}
}
else
{
$returnValue = 'Class does not exist';
}
}
else
{
$returnValue = 'No action given';
}

if(is_object($returnValue) || is_array($returnValue))
{
echo json_encode($returnValue);
}
else
{
$returnArr = array('message'=>$returnValue);
echo json_encode($returnArr);
}
?>

myclassname.class.php

<?php
class myclassname
{
private $pa;
function __construct($postArray = array())
{
$this->pa = $postArray;
}

function myclassmethod_string()
{
return 'Your name is '.$this->pa['name'];
}

function myclassmethod_array()
{
$myArr = array('Peter'=>'35', 'Ben'=>'37', 'Joe'=>'43');
return $myArr;
}

function myclassmethod_object()
{
$myObj = (object) array('Peter'=>'35', 'Ben'=>'37', 'Joe'=>'43');
return $myObj;
}

function __destruct()
{

}
}
?>

Monday, 6 October 2014

Using PHP to get YouTube Channel feed into Twitter Bootstrap thumbnails

I've been working on a Twitter Bootstrap site. The client created a YouTube channel and wanted the feed coming into the site. Some of the videos added are uploaded by the users, some come from subscriptions. There is a nice class called thumbnail in Twitter Bootstrap for such things, so I thought I'd use that. I'm happiest getting external data using PHP. Here's how it's done.
Replace the word 'Google' with the name of your channel.
<?php
$url = 'https://gdata.youtube.com/feeds/api/videos?q=Google&max-re%20sults=5&v=2&alt=jsonc&orderby=published';
$json = file_get_contents($url);
$data = json_decode($json);
$items = $data->data->items;
foreach($items as $child)
{
echo '<a href="'.$child->player->default.'" class="thumbnail">';
echo '<h4>'.$child->title.'</h4>';
echo '<img src="'.$child->thumbnail->sqDefault.'" alt="'.$child->title.'" />';
echo '<footer>'.date("jS F Y",strtotime($child->updated)).'</footer>';
echo '</a>';
}
?>

Monday, 1 October 2012

Simple JSON retrieval through jQuery

This page explains how to retrieve some simple JSON data and append it to a page. First the JSON through a script called jsonout.php

{
  "one": "Singular sensation",
  "two": "Beady little eyes",
  "three": "Little birds pitch by my doorstep"
}


Now the HTML with jQuery to retrieve and display it within the page.


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Simple JSON retrieval through jQuery</title>
<!--[if IE]>
 <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link rel="stylesheet" href="http://meyerweb.com/eric/tools/css/reset/reset.css" />
<style>
body
{
font:10px/15px Sans-serif;
}
</style>
<script src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1"); 
</script>
</head>
<body>
<script>
(function()
{
$.getJSON('jsonout.php', function(data)
{
  $.each(data, function(key, val)
  {
    $('body').append('<p>'+key+':'+val+'</p>');
  });
});
})();
</script>
</body>
</html>

Friday, 22 July 2011

Lorem and Gibberish through PHP using the randomtext.me JSON API

Crikey! Is it so long since I did a post. OK. Here is yet another way of getting Lorem Ipsum or Gibberish to your page, while you test it out. There is a great generator at http://www.randomtext.me/ and they have helpfully supplied us with a JSON based API.

Below is an example ho grabbing 7 paragraphs of gibberish between 30 and 50 characters long. I then echo them to the page.


<?php
$data = json_decode(file_get_contents("http://www.randomtext.me/api/gibberish/p-7/30-50"));
echo $data->text_out;
?>

Tuesday, 28 June 2011

PHP, JSON basic example using Topsy Otter

Topsy Otter

Otter API is a RESTful HTTP web service to Topsy. Topsy is a search engine that ranks links, photos and tweets by the number and quality of retweets they receive. The quality of retweets is determined by the influence of the Twitter users.

Below I have used PHP to display results of an Otter call which returns JSON. The results are for the most popular stories on wired.com today.

<?php
$data = json_decode(file_get_contents("http://otter.topsy.com/search.json?q=site:wired.com&window=d"));

foreach ($data as $name => $value)
{
 echo $value->total.'<br />';
 getAllItems($value->list);
}

function getAllItems($iarr)
{
foreach((array)$iarr as $itemName => $itemValue)
{
echo $itemValue->content.'<br />';
}
}
?>

PHP, JSON basic example using delicious

Here is an example of extracting and displaying JSON results through PHP. In this instance, I am using my delicious feed.
Having received the data and decoded it into an array, I like to see the structure of the data. This is where the <pre> tags come in handy. Once you have seen the structure, you know how to traverse and pick out the values you need. Given that the code below is so small, I have commented it.



<?php
/* Get the data and put it into an array */
$data = json_decode(file_get_contents("http://feeds.delicious.com/v2/json/guitarbeerchocolate"));

/* Display the structure of the data so that we know what to extract */
/* Comment out once understood */
echo '<pre>';
print_r($data);
echo '</pre>';

/* Traverse the array, picking out the values you need */
foreach ($data as $name => $value)
{
echo $value->u.'<br />';
echo $value->d.'<br />';
getAllItems($value->t);
echo $value->dt.'<br />';
echo $value->n.'<br />';
echo $value->a.'<br />';
}

/* Some values in this case, tags are themselves arrays so traverse those too */
function getAllItems($iarr)
{
foreach($iarr as $item)
{
echo $item.', ';
}
echo '<br />';
}
?>