Now keep in mind I haven't touched the code on the server, so I did nothing to cause it to now fail. The problem is that my server is actually on a shared host, and is potentially subject to the hosting company making configuration changes without me necessarily knowing about it. And for some reason they decided to tighten up some of the PHP security settings. The end result is that the simplexml_load_file() function won't work - I get this warning:
If you're getting this warning instead of seeing YouTube videos at the bottom of Aliens Abducted Me, don't despair. The same problem just bit me and there is a work-around. The best fix is to ask your web hosting company or web server admin to change a PHP configuration setting to allow the simplexml_load_file() function to work. If they're willing, ask them to change the allow_url_fopen setting in the php.ini file to ON. But there's a good chance they won't be so helpful, in which case you need to go to option 2, as I did.
Option 2 is to sidestep simplexml_load_file() entirely, and use a different approach to loading XML data. The approach involves using the Client URL library, also known as cURL, which is built into PHP. cURL is extremely flexible, allowing you to communicate with all kinds of different servers using lots of different protocols. In our case, we just want to use cURL to load a file from a URL, and then we can pull it into an XML object. Here's a reusable PHP function that uses cURL to load any kind of data from a URL:
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_REFERER, 'http://www.headfirstlabs.com/');
$str = curl_exec($curl);
Change the URL in the line with the Head First Labs URL to your own - this just lets the server know who generated the request (some servers, like Google News, require you to provide this). Now we need one more function to actually load an XML file from a URL into an XML object in PHP:
Stick those two functions in your PHP code, or into a reusable script that you pull in with require_once, and you're ready to roll. Then just replace the call to simplexml_load_file() to load_xml_from_url():
It reuses our general load_file_from_url() function to keep from duplicating the cURL loading code. To see this function in action with JSON data, check out this post.