php 加载外部 xml 文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5434142/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Load external xml file?
提问by Richard Hedges
I have the following code (from a previous question on this site) which retrieves a certain image from an XML file:
我有以下代码(来自本网站上一个问题),它从 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'];
}
?>
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?
我想知道的是,如何加载外部 XML 文件而不是像上面显示的那样在实际的 PHP 中写入 XML 数据?
回答by cantlin
Procedurally, simple_xml_load_file.
程序上,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.
您可能还需要考虑使用 OO 接口SimpleXMLElement。
Edit:If the file is at some remote URI, file_exists
won't work.
编辑:如果文件位于某个远程 URI,file_exists
则不起作用。
$file = 'http://example.com/text.xml';
if(!$xml = simplexml_load_file($file))
exit('Failed to open '.$file);
print_r($xml);
回答by pderaaij
You can use simplexml_load_file
您可以使用simplexml_load_file
回答by Imi Borbas
$xml = simplexml_load_file('path/to/file');
$xml = simplexml_load_file('path/to/file');