使用PHP制作AJAX请求API [关闭]

I'm trying to make an API for my web site using PHP, since the site is coded in PHP, so the developers can get information using AJAX Requests to my server, but how I can make this?

Update: Any sites where I can get examples?

Like any regular form processing. The difference is that you typically return JSON instead of HTML when it is an API to be used with AJAX requests:

<?php
header("Content-Type: application/json");
print json_encode(array("sum" => $_GET["a"] + $_GET["b"]));

That would be a simple addition API. Which is obviously a silly example. It very much depends on what you want to accomplish with your API, and what data your site actually handles.

Create a normal PHP page. Only, instead of returning HTML like a typical PHP page does, have it return an XML or JSON response.

If you want that other Developers can Access this page directly with an Ajax-Request you should set Access Control for Cross-Site Requests. You can read About it here:

http://www.w3.org/TR/2008/WD-access-control-20080912/

php:

header('Access-Control-Allow-Origin: *');

Then you should decide how you send your Data (XML, JSON, CSV, etc.) and set this as Content-Type in your header. I recommend JSON because it is easy to handle with PHP and JavaScript. The rest is like every other page you publish to the world.

php:

header("Content-Type: application/json");

I know I'm a few years too late but hopefully this'll help a few other people out. I set up a simple javascript-to-php api structure which allows you to make simple api requests and keeps the code for your backend from being publicly exposed. You can find it here