简体   繁体   中英

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?

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

您可以使用simplexml_load_file

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM