Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load external xml file?

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?

like image 237
Richard Hedges Avatar asked Mar 25 '11 14:03

Richard Hedges


People also ask

Can you open an XML file in a browser?

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".

How do I open an XML file on a PC?

#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.


1 Answers

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);
like image 67
cantlin Avatar answered Oct 12 '22 23:10

cantlin