Load external xml file?

26,829

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

Solution 2

You can use simplexml_load_file

Solution 3

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

Share:
26,829
Richard Hedges
Author by

Richard Hedges

Updated on January 29, 2020

Comments

  • Richard Hedges
    Richard Hedges over 4 years

    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?