It’s time for another WordPress Development Tip, today is a not so well known function, wp_remote_fopen.
When I search the internet for WordPress tips and tricks, I usually encounter small tutorials and tips that use either file_get_contents or cURL. The first, file_get_contents is a PHP function, which is usually turned off by most web hosting companies.
cURL is an extension built into PHP, and usually works on most web hosts, but it requires a bit more tweaking and coding to use. If you need to send parameters along with your external call, such as login and password for Twitter, or something else, then you are best suited by using cURL for this. (See my other post on how to check if cURL is available: How To Check if the cURL PHP extension is loaded.)
However, if all you want is to download the content of a URL, you should use wp_remote_fopen, which is a built in function in WordPress with redundancy built in.
Redundancy?
Yes, the function first tries to load the external content via fopen (PHP) and then cURL if the first call fails. This means that using this WordPress function ensures it works on most web hosts. (Note: MOST!)
Returns the contents of a remote URI. Tries to retrieve the HTTP content with fopen first and then using cURL, if fopen can’t be used.
From WordPress Codex
How to use?
The function is really easy to use:
$url = "http://mywordpress.com"; $content = wp_remote_fopen($url);
BUT, I really recommend you add some error-checking, perhaps something like:
$url = "http://mywordpress.com";
$content = wp_remote_fopen($url);
if ($content<>'') {
// Do whatever you want with the content here...
} else {
// Woops, I think something is going wrong!
}
I hope you enjoyed this little tip, and perhaps take a look at the other developer tips in the WordPress Development Tips category.
2 Responses
Leave a Reply
this would load an entire page from the URL from the to the and then you would parse whatever info out of the result?
Spot on, my young padiwan
There are also similar functions for RSS feeds, with methods to enable caching so you don’t request information too often from the poor RSS feeds.