【问题标题】:best way to check if xml (without file extension) exists检查xml(没有文件扩展名)是否存在的最佳方法
【发布时间】:2016-02-04 07:47:59
【问题描述】:

很遗憾,我现在无法检查它,因为 XML (将在另一台服务器上) 处于脱机状态。 xml 文件的 url 如下所示:http://url.com:123/category?foo=bar。如您所见,它没有 .xml 文件扩展名。我忘记插入文件检查以避免错误消息打印出 xml 文件的 url。
simple_load_file 可以正常使用该 URL,但我不确定 file_exists!

这行得通吗?:

if(file_exists('http://url.com:123/category?foo=bar')) { 
$xml = simplexml_load_file('http://url.com:123/category?foo=bar');
//stuff happens here
} else{echo 'Error message';}

我不确定,因为 file_exists 不适用于 URL。 谢谢!

【问题讨论】:

    标签: php xml url file-exists


    【解决方案1】:

    正如您所怀疑的,file_exists() 不适用于 URL,但 fopen()fclose() 可以:

    if (fclose(fopen("http://url.com:123/category?foo=bar", "r"))) {
        $xml = simplexml_load_file('http://url.com:123/category?foo=bar');
        //stuff happens here
    } else {
        echo 'Error message';
    }
    

    【讨论】:

      【解决方案2】:

      如果你只是尝试获取数据来解析它,它并不是很有用。特别是如果您调用的 URL 是程序/脚本本身。这只是意味着脚本被执行了两次。

      我建议您使用file_get_contents() 获取数据,处理/捕获错误并解析获取的数据。

      只是阻止错误:

      if ($xml = @file_get_contents($url)) {
        $element = new SimpleXMLElement($xml);
        ...
      }
      

      【讨论】:

      • 这是有道理的,因为 XML 可以变得相当长。谢谢。
      猜你喜欢
      • 2011-01-14
      • 1970-01-01
      • 2015-09-05
      • 1970-01-01
      • 2013-07-18
      • 1970-01-01
      • 1970-01-01
      • 2010-09-18
      相关资源
      最近更新 更多