How to Set Local Time with PHP
PHP, MySQL, JavaScript & HTML5 All-in-One For Dummies Cheat Sheet
How to Create an HTML Table

How to Use PHP to Return the Date in JSON Format

JavaScript Object Notation (JSON) is a means to exchange data between web services in a simple and succint manner, without all of the overhead of XML. JSON is a great way to integrate a web service with JavaScript because JSON can be easily parsed by JavaScript code. Even better, PHP includes native functions to both create and read JSON.

These functions, json_encode() and json_decode(), make it easy to work with JSON and create JSON web services from PHP.

A simple way to get your feet wet with web services is to return a date in JSON format. Here's how you can do that:

  1. Open your text editor or programming IDE and create a new empty file.

  2. Place the following code within the file:

    $header = "Content-Type: application/json";
    $date = date("M d, Y");
    print json_encode($date);
  3. Save the file as date.php in your web server's document root.

  4. View the page in your web browser at http://localhost/date.php.

    You should see a page like that shown here (though the date will probably be different).


    The page contains a JSON-encoded date. This date could then be parsed with JavaScript or even consumed from another PHP program. Note the use of application./json as an HTTP header. This is critically important to inform the calling program (whether JavaScript or PHP) that it should expect to receive a JSON response as opposed to HTML, XML, or another type of response.

  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
How to Create a PHP Class
How to Use JavaScript's GetElementById to Access a Specific Element
How to Query with the mysql Client