PHP: Importing Remote XML To an Array

XML. Your friend, your enemy. Perhaps it’s overused, but do enough work with a few 3rd party systems and you’d better have a solution for throwing XML into an array.There is a potential misuse of fopen() to call external XML’s and many hosted service providers will forbid you from using it to call external files. Therefore, I humbly suggest using CURL to do your dirty work. It’s a few extra lines of code, but it’s worth it.


//the location of your external XML file. Basic HTTP Auth can be added if necessary
$url = “https://someurl.com/somefile.xml”; //grab the XML and save it to a temp XML file
$ch = curl_init($url);
$fp = fopen(“temp.xml”, “w”);
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);

//Load the local XML that was created in the above CURL call
$xml = simplexml_load_file(“temp.xml”)
or Die (‘ERROR: Could not load file’);print_r($xml);

Hi there, I'm Jon.

Writer. Musician. Adventurer. Nerd.

Purveyor of GIFs and dad jokes.