【问题标题】:Load external xml file?加载外部 xml 文件?
【发布时间】:2011-03-25 14:53:48
【问题描述】:

我有以下代码(来自本网站上一个问题),它从 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 数据?

【问题讨论】:

    标签: php xml file external


    【解决方案1】:

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

    【讨论】:

    • file_exists 正在本地系统上检查该文件,由于该文件存在于远程服务器上,因此无法执行此操作。
    【解决方案2】:

    您可以使用simplexml_load_file

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-09-19
        • 2013-12-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-07-30
        相关资源
        最近更新 更多