Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

REST API in PHP output to JSON file extension

Tags:

json

rest

file

php

api

So I want to write a REST API in PHP for JSON for consumption on the iPhone, but also a lot of websites and devices. I have the below code, when accessed via a GET statement, returns a file like:

1mdi2o3.part

How do I return something like: users.json

$db->setQuery( "SELECT * FROM users");
$db->query() or die($queryError);
$numRows = $db->getNumRows();
$row = $db->loadObjectList();

// PRINT JSON FILE
header("Content-type: application/json");

for($i = 0 ; $i < $numRows; $i++){
$json_output[$i] = $row[$i];
}

$MYjson_output = json_encode($json_output);

echo $MYjson_output;
like image 691
Brian H Avatar asked Jan 30 '10 22:01

Brian H


1 Answers

Not entirely such what your goal is but here are 3-4 solutions that might work:

Common Solutions

Rewrite

This is probaly the most conventional way of getting clean URIs for your API. If you want the user part of user.json to be dynamic, you can use mod_rewrite (again assuming Apache) to rewrite your URLs to a php handler script. If you are going the conventional RESTful style URL route, you will probably want to use this anyway to achieve clean / separated URLs.

# For grabbing all users
RewriteEngine on
RewriteRule ^users\.json rest.php [L]

# For grabbing one particular user
RewriteEngine on
RewriteRule ^([a-z0-9]+)\.json rest.php?user=$1 [L]

Where rest.php is your PHP handler script.

URL Rewriting without mod-rewrite

If you don't want to use mod_rewrite, you can also do something like

example.com/rest.php/users.json
example.com/rest.php/user-id.json

or even

example.com/rest.php/user-id
example.com/rest.php/user/user-id

Where rest.php is your PHP handler script. You can grab the user-id from the URL (or URI if we're talking RESTful terms) using the $_SERVER global with $_SERVER['REQUEST_URI'].

Other solutions

Changing download name via Content-Disposition:

I believe you want to add the Content-Disposition header...

<?php
    header('Content-Disposition: attachment; filename="users.json"');
?>

This will force the file to be downloaded as user.json. This usually isn't the behavior expected for a REST API, but from the way your question was worded, I figured I'd throw it out there.

AddHandler (or AddType)

Assuming you're running an Apache server, you can also just use AddHandler directive to make .json extension files be treated like they are php.

AddHandler application/x-httpd-php .json

Warning: Other plain .json files will be treated as PHP so you'd probably want to set this in a .htaccess file in the directory with the PHP script. This would work fine for this one URI but not ideal if you were exposing many URIs

like image 78
nategood Avatar answered Oct 05 '22 22:10

nategood