gpt4 book ai didi

php - 检查 url 是否有效以及 php 中的有效 XML

转载 作者:可可西里 更新时间:2023-11-01 00:35:49 24 4
gpt4 key购买 nike

我想阅读 rss 提要并存储它。为此,我正在使用:-

<?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.然后检查文件(http://www.forbes.com/news/index.xml) 是否有有效的XML 数据。如果 XML 有效则显示响应时间,否则显示错误。

我的问题的答案:

谢谢大家的帮助和建议,我解决了这个问题。为此我写了这段代码

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

}



?>

最佳答案

如果 url 无效,file_get_contents 将失败。

检查xml是否有效

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

如果是则返回真,否则将完全失败。

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

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

关于php - 检查 url 是否有效以及 php 中的有效 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8035675/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com