Useful Snippets

Welcome!


This blog is used to collect useful snippets related to Linux, PHP, MySQL and more. Feel free to post comments with improvements or questions!

Are your smart devices spying on you? Make better purchasing choices and find products that respect your privacy at Unwanted.cloud

RSS Latest posts from my personal blog


Subscribe to RSS feed


Working with APIs that return different output formats depending on Accept HTTP header in PHP

Stanislav KhromovStanislav Khromov

Most APIs let you specify the return type you want with a parameter, ie:

http://api.site.com/get/stuff?output=xml

However, some APIs will return the format that you specify in the HTTP accept header instead. So the URL would always be:

http://api.site.com/get/stuff

But depending on the HTTP Accept header, the API returns different data back.
Here is how to force XML or JSON output for such an API.

XML

$context = stream_context_create(
    array(
        'http' => array(
            'header' => "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n",
        )
    )
);
$jobs_raw = file_get_contents('http://api.site.com/get/stuff', null, $context);

JSON

$context = stream_context_create(
    array(
        'http' => array(
            'header' => "Accept: application/json, application/javascript\r\n",
        )
    )
);
$jobs_raw = file_get_contents('http://api.site.com/get/stuff', null, $context);

Source

PHP

Full-stack impostor syndrome sufferer & Software Engineer at Schibsted Media Group

Comments 0
There are currently no comments.