Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Building a Web Application with PHP and MariaDB: A Reference Guide

You're reading from   Building a Web Application with PHP and MariaDB: A Reference Guide Build fast, secure, and interactive web applications using this comprehensive guide

Arrow left icon
Product type Paperback
Published in Jun 2014
Publisher
ISBN-13 9781783981625
Length 200 pages
Edition 1st Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Sai S Sriparasa Sai S Sriparasa
Author Profile Icon Sai S Sriparasa
Sai S Sriparasa
Arrow right icon
View More author details
Toc

Table of Contents (12) Chapters Close

Preface 1. CRUD Operations, Sorting, Filtering, and Joins 2. Advanced Programming with MariaDB FREE CHAPTER 3. Advanced Programming with PHP 4. Setting Up Student Portal 5. Working with Files and Directories 6. Authentication and Access Control 7. Caching 8. REST API 9. Security 10. Performance Optimization Index

Generating JSON feeds


In the last section, we used PHP's SimplXMLElement class to generate our XML feeds. In this section, we will use PHP's json_encode function to generate our JSON feed. Building a JSON feed is very simple when compared to building the XML feed. JSON is a very popular data exchange format and is considered lightweight when compared to XML, as shown in the following code snippet, present in the controllers/api.php file:

private function _generateJSON($root, $data){
  header("HTTP/1.1 200 OK");
  header("Content-Type: application/json");
  echo json_encode(array($root=>$data));
}

In this snippet, we begin by building our _generateJSON method that will expect the name of the endpoint and the data that was fetched by the get action. Now, let's modify the get action to use the _generateJSON method, as shown in the following code snippet:

if(strlen($method)>0){
  $data = $this->model->$method();

  if(is_array($data) && count($data) >0){
    $this->_generateJSON...
lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime