如果第一个XML为空,则加载另一个


If 1st XML is empty then load a different one

我正在获取xml提要的内容,并使用php:在我的网页上打印标题

                $url = 'http://site.com/feed';
                $xml = simplexml_load_file($url);
                foreach($xml->ART as $ART) {
                    echo $ART->TITLE;
                }

我希望能够设置备份,所以如果没有找到第一个xml,就会加载另一个xml。

我尝试了以下代码,但它不起作用。如果找不到提要,页面会显示"XML解析错误:",我想这与什么都不一样。

                if ($url != '') {
                    $xml = simplexml_load_file($url);
                } else {
                    //Here I would load a different xml file. 
                }

我该怎么办?我应该写条件php来检查第一个url是否包含TITLE,如果不加载第二个url吗?

感谢

更新这把我的整个页面搞砸了:

                $first_url = 'http://site.com/feed1';
                $second_url = 'http://site.com/feed2';

                // if URL wrappers is enabled
                if (is_url($first_url))
                {
                  // parse first url
                  $xml = simplexml_load_file($first_url);
                }
                else
                {
                  // parse second url
                  $xml = simplexml_load_file($second_url);
                }

                foreach($xml->ART as $ART) {
                    echo $ART->TITLE;
                }

请参阅simplexml_load_file

返回SimpleXMLElement类的对象,该对象的属性包含XML文档中保存的数据。出现错误时,它将返回FALSE。

php.net 示例

<?php
 // The file test.xml contains an XML document with a root element
 // and at least an element /[root]/title.
  if (file_exists('test.xml')) {
    $xml = simplexml_load_file('test.xml');
    print_r($xml);
  } else {
     exit('Failed to open test.xml.');
  }
?>

编辑:你可以做

$url = 'http://site.com/feed';
            if( $xml = simplexml_load_file($url) ) {
                 foreach($xml->ART as $ART) {
                      echo $ART->TITLE;
                  }
            } else {
              //parsing new url
            }
function parse_xml($url)
{
  // your code
}
try
{
  parse_xml($first_url);
}
catch (Exception $e)
{
  parse_xml($second_url); 
}

或者,您可以在进行解析之前检查URL是否返回XML:-

// if URL wrappers is enabled
if (is_url($first_url))
{
  // parse first url
  $xml = simplexml_load_file($first_url);
}
else
{
  // parse second url
  $xml = simplexml_load_file($second_url);
}

我认为它可以使用:

                $url = 'site.com/feed1';
                $xml = simplexml_load_file($url);
                if ($xml == null) {
                    $url = 'site.com/feed2';
                    $xml = simplexml_load_file($url);
                    }
                foreach($xml->ART as $ART) {
                    echo $ART->TITLE;
                }