How to Fix "simplexml_load_file(): I/O warning: failed to load external entity '...'" PHP Warning?

If you see the following error/warning when using the simplexml_load_file() function:

Warning: simplexml_load_file(): I/O warning : failed to load external entity "..." in /path/to/file.php on line ...

Then it means that you have likely provided the XML you wish to load from a file as a string to the simplexml_load_file() function argument (instead of the path to that XML file). It could, for example, happen in the following case:

$xmlStr = file_get_contents('/path/to/file.xml');
$xml = simplexml_load_file($xmlStr);
// ...

In the example above, using the file_get_contents() function returns a string of loaded XML. When you provide that as an argument to the simplexml_load_file() function, it throws a warning because it is expecting the path of the XML file as an argument and not a string. To solve this, you can do any of the following:

Use the XML String With SimpleXMLElement Object Instance

You could, for example, use file_get_contents() to first load the XML file into a string, and then provide that as an argument to the SimpleXMLElement object instance. For example:

$xmlStr = file_get_contents('/path/to/file.xml');
$xml = new SimpleXMLElement($xmlStr);
// ...

Load the XML File Directly With simplexml_load_file()

You could directly provide the XML file path to the simplexml_load_file() function, and it will return a SimpleXMLElement object instance on success (and false on failure). For example:

$xml = simplexml_load_file('/path/to/file.xml');
// ...

Use the XML String With simplexml_load_string()

You could, for example, use file_get_contents() to first load the XML file into a string, and then provide that as an argument to the simplexml_load_string() function — which would interpret the string of XML into a SimpleXMLElement object instance on success (and return false on failure). For example:

$xmlStr = file_get_contents('/path/to/file.xml');
$xml = simplexml_load_string($xmlStr);
// ...

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.