PHP rest API returning JSON for webpages

I am developing a PHP restful API which is returning a JSON response. This is currently for native mobile app consumption (iOS/Android).

My question, is it possible to use the same restful API for website consumption? or do I need to support HTML response from the restful API as well as JSON? How do you get a JSON response from a web service to display as a webpage? or do I need to implement output formatters as part of the framework to respond as HTML when required?

I have tried to search for answers to this question but I couldn't find any useful answer.


Emm... As theory, for example you can make it like this:

class MyOutput
{
    const CTX_HTML = 1;
    const CTX_JSON = 2;
    //const CTX_XML = 3;
    //const CTX_CLI = 4;
    //const CTX_ETC = N;

    private $_data = null;

    public function __construct()
    {
        $this->_data = new StdClass();
    }
    public function __set($prop, $value)
    {
        $this->_data->{$prop} = $value;
    }
    public function render($context)
    {
        if ($context == self::CTX_JSON) {
            header('Content-Type: application/json');
            echo json_encode($this->_data);
        } else {
            header('Content-Type: text/html');
            // TODO extract/pass data into layout/template
        }
    }
}


$Output = new MyOutput();

$Output->foo = 1;
$Output->bar = 2;
$Output->render(MyOutput::CTX_JSON);
$Output->render(MyOutput::CTX_HTML);

But i think API should be place on separated host. Because this is different applications.


you can create API that returns XML and from XML using XSL construct HTML

This link gonna be helpful:

http://www.htmlgoodies.com/beyond/xml/converting-xml-to-html-using-xsl.html

链接地址: http://www.djcxy.com/p/45654.html

上一篇: 在ASP.NET Web API中返回错误的最佳做法

下一篇: PHP rest API返回JSON的网页