Ric*_*ges 5 php xml file external
我有以下代码(来自此网站上的上一个问题),它从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'];
}
?>
Run Code Online (Sandbox Code Playgroud)
我想知道的是,如何加载外部XML文件而不是像上面显示的那样在实际的PHP中编写XML数据?
can*_*lin 14
程序上,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);
}
Run Code Online (Sandbox Code Playgroud)
您可能还想考虑使用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);
Run Code Online (Sandbox Code Playgroud)