2011-03-25 167 views
5

我有以下代码(从这个网站上一个问题),它从一个XML文件中检索某个图像:加载外部xml文件?

<?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']; 
} 

?> 

我想知道的是,我怎么能加载外部XML文件而不是像上面显示的那样在实际的PHP中编写XML数据?

回答

12

在程序上,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); 
} 

您可能还想考虑使用OO接口SimpleXMLElement

编辑:如果文件位于某个远程URI,则file_exists将不起作用。

$file = 'http://example.com/text.xml'; 
if(!$xml = simplexml_load_file($file)) 
    exit('Failed to open '.$file); 
print_r($xml); 
+0

'file_exists'正在检查本地系统上的该文件,而该文件无法执行,因为该文件存在于远程服务器上。 – cantlin 2011-03-25 15:11:53

+0

谢谢Dae! :) 我相信它现在工作 – 2011-03-25 15:20:51

2

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