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


Most viewed posts


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

Web Developer at Aftonbladet (Schibsted Media Group)
Any opinions on this blog are my own and do not reflect the views of my employer.
LinkedIn
Twitter
WordPress.org Profile
Visit my other blog

Comments 0
There are currently no comments.