I have the following code (from a previous question on this site) which retrieves a certain image from an XML file:
<?php
$string = <<<XML
<?xml version='1.0'?>
<movies>
<movie>
<images>
<image type="poster" url="http://cf1.imgobject.com/posters/b7a/4bc91de5017a3c57fe00bb7a/i-am-legend-original.jpg" size="original" width="675" height="1000" id="4bc91de5017a3c57fe00bb7a"/>
<image type="poster" url="http://cf1.imgobject.com/posters/b7a/4bc91de5017a3c57fe00bb7a/i-am-legend-mid.jpg" size="mid" width="500" height="741" id="4bc91de5017a3c57fe00bb7a"/>
<image type="poster" url="http://cf1.imgobject.com/posters/b7a/4bc91de5017a3c57fe00bb7a/i-am-legend-cover.jpg" size="cover" width="185" height="274" id="4bc91de5017a3c57fe00bb7a"/>
</images>
</movie>
</movies>
XML;
$xml = simplexml_load_string($string);
foreach($xml->movie->images->image as $image) {
if(strcmp($image['size'],"cover") == 0)
echo $image['url'];
}
?>
What I'd like to know is, how can I load the external XML file rather than writing the XML data in the actual PHP like is shown above?
View an XML file in a browser If all you need to do is view the data in an XML file, you're in luck. Just about every browser can open an XML file. In Chrome, just open a new tab and drag the XML file over. Alternatively, right click on the XML file and hover over "Open with" then click "Chrome".
#1) Open Windows Explorer and browse to the location where the XML file is located. We have browsed to the location of our XML file MySampleXML as seen below. #2) Now right-click over the file and select Open With to choose Notepad or Microsoft Office Word from the list of options available to open the XML file.
Procedurally, simple_xml_load_file.
$file = '/path/to/test.xml';
if (file_exists($file)) {
$xml = simplexml_load_file($file);
print_r($xml);
} else {
exit('Failed to open '.$file);
}
You may also want to consider using the OO interface, SimpleXMLElement.
Edit: If the file is at some remote URI, file_exists
won't work.
$file = 'http://example.com/text.xml';
if(!$xml = simplexml_load_file($file))
exit('Failed to open '.$file);
print_r($xml);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With