加载外部XML文件? [英] Load external xml file?

查看:137
本文介绍了加载外部XML文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从下面的代码(从这个网站上的一个问题),从XML文件中检索一个特定的图像:

 <?php 
$ string =<<< XML
<?xml version ='1.0'?>
<电影>
< movie>
<图片>
< image type =posterurl =http://cf1.imgobject.com/posters/b7a/4bc91de5017a3c57fe00bb7a/i-am-legend-cover.jpgsize =coverwidth =185 height =274id =4bc91de5017a3c57fe00bb7a/>
< /图片>
< / movie>
< /电影>
XML;

$ xml = simplexml_load_string($ string);
$ b foreach($ xml->影片 - >影像 - >影像为$影像){

if(strcmp($ image ['size'],封面)== 0)
echo $ image ['url'];
}

?>

我想知道的是,如何加载外部XML文件而不是写入实际PHP中的XML数据如上所示?解析方案

过程式地,simple_xml_load_file

  $ file =' /path/to/test.xml'; 
if(file_exists($ file)){
$ xml = simplexml_load_file($ file);
print_r($ xml);
} else {
exit('无法打开'。$ file);



$ b您可能还想考虑使用OO接口简单的XML元素



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

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


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

这篇关于加载外部XML文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆