Load external xml file?

2020-03-23 02:51发布

问题:

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?

回答1:

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);


回答2:

You can use simplexml_load_file



回答3:

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