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.