Chapter 11. Talking to Other Websites and Services

Previous chapters discussed external sources of data such as databases and files. This chapter is about another important external source of data: other websites. PHP programs are often clients of other sites or APIs that offer up data that you need. Your website could itself serve up data to another site that needs it. This chapter shows how to retrieve external URLs and access APIs. It also explains what you need to do to serve API requests to others.

The first section shows how to use PHP’s built-in file access functions with URLs instead of filenames. This is a convenient option for quick and easy remote URL access. For more power and flexibility, though, use PHP’s cURL extension, discussed in “Comprehensive URL Access with cURL”. The cURL functions let you control many different aspects of the requests you’re making.

Serving up API responses instead of web pages from your PHP program is the focus of “Serving API Requests”. These responses are similar to standard HTML pages but have some important differences.

Simple URL Access with File Functions

An extremely convenient aspect of file access functions like file_get_contents() is that they understand URLs in addition to local filenames. Grabbing a remote URL and putting it into a string is just a matter of handing that URL to file_get_contents().

Example 11-1 uses file_get_contents() to display an interesting fact from the website numbersapi.com about September ...

Get Learning PHP now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.