2011-11-07 75 views
3

我想读一个RSS提要,并储存it.for这个我米使用: -检查网址是否有效,并在PHP有效的XML

<?php 
$homepage = file_get_contents('http://www.forbes.com/news/index.xml'); 
$xml = simplexml_load_string($homepage); 
echo '<pre>'; 
print_r($xml); 
?> 

但首先我要检查

1.URL是有效还是无效,意味着如果的

$homepage = file_get_contents('http://www.forbes.com/news/index.xml'); 

其响应时间小于1分钟,URL地址是正确的

2.然后检查File(http://www.forbes.com/news/index.xml)是否有有效的XML数据。 如果有效的XML则显示响应时间,否则显示错误。

回答我的问题:

感谢大家对你的帮助和suggestion.I解决了这个问题。为了这个,我写了这个代码

<?php 
// function() for valid XML or not 
function XmlIsWellFormed($xmlContent, $message) { 
libxml_use_internal_errors(true); 

$doc = new DOMDocument('1.0', 'utf-8'); 
$doc->loadXML($xmlContent); 

$errors = libxml_get_errors(); 
if (empty($errors)) 
{ 
    return true; 
} 

$error = $errors[ 0 ]; 
if ($error->level < 3) 
{ 
    return true; 
} 

$lines = explode("r", $xmlContent); 
$line = $lines[($error->line)-1]; 

$message = $error->message . ' at line ' . $error->line . ': ' . htmlentities($line); 

return false; 
} 
    //function() for checking URL is valid or not 
    function Visit($url){ 
    $agent = $ch=curl_init(); 
    curl_setopt ($ch, CURLOPT_URL,$url); 
    curl_setopt($ch, CURLOPT_USERAGENT, $agent); 
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); 
    curl_setopt ($ch,CURLOPT_VERBOSE,false); 
    curl_setopt($ch, CURLOPT_TIMEOUT, 60); 
    curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, FALSE); 
    curl_setopt($ch,CURLOPT_SSLVERSION,3); 
    curl_setopt($ch,CURLOPT_SSL_VERIFYHOST, FALSE); 
    $page=curl_exec($ch); 
    //echo curl_error($ch); 
    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE); 
    curl_close($ch); 
    if($httpcode>=200 && $httpcode<300) return true; 
    else return false; 
    } 
     $url='http://www.forbes.com/news/index.xml'; 
     if (Visit($url)){ 
    $xmlContent = file_get_contents($url); 

     $errorMessage = ''; 
     if (XmlIsWellFormed($xmlContent, $errorMessage)) { 
     echo 'xml is valid'; 
     $xml = simplexml_load_string($xmlContent); 
     echo '<pre>'; 
     print_r($xml); 
     } 

    } 



?> 

回答

4

如果url无效file_get_contents会失败。

要检查是否XML是有效的

simplexml_load_string(file_get_contents('http://www.forbes.com/news/index.xml')) 

都将返回true,如果它,如果它不将完全失败。

if(simplexml_load_string(file_get_contents('http://www.forbes.com/news/index.xml'))){ 

     echo "yeah"; 
    }else { echo "nah";} 
+0

谢谢,您guideness .... – omnath

1

page具有对使用正则表达式的URL验证程序的一个片段。功能和用法:

function isValidURL($url) 
{ 
    return preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $url); 
} 

if(!isValidURL($fldbanner_url)) 
{ 
    $errMsg .= "* Please enter valid URL including http://<br>"; 
}