假设我只想从远程服务器加载最多 10MB 的 XML 文件。
类似于
$xml_file = "http://example.com/largeXML.xml";// size= 500MB
//PRACTICAL EXAMPLE: $xml_file = "http://www.cs.washington.edu/research/xmldatasets/data/pir/psd7003.xml";// size= 683MB
/*GOAL: Do anything that can be done to hinder this large file from being loaded by the DOMDocument without having to load the File n check*/
$dom = new DOMDocument();
$dom->load($xml_file /*LOAD only IF the file_size is <= 10MB....else...echo 'File is too large'*/);
如何才能实现这个可能?...有什么想法或替代方案吗?或实现这一目标的最佳方法将受到高度赞赏。
我检查了PHP: Remote file size without downloading file但是当我尝试使用类似的东西时
var_dump(
curl_get_file_size(
"http://www.dailymotion.com/rss/user/dialhainaut/"
)
);
我得到字符串“未知”(长度=7)
当我按照下面的建议尝试使用 get_headers
时, header 中缺少 Content-Length,因此这也无法可靠地工作。
请告知如何确定长度
,并避免在超过10MB
时将其发送到DOMDocument
最佳答案
好的,终于可以工作了。 header 解决方案显然不会广泛工作。在此解决方案中,我们打开一个文件句柄并逐行读取 XML,直到达到 $max_B 的阈值。如果文件太大,我们仍然需要读取它直到 10MB 标记,但它会按预期工作。如果文件小于 $max_B,则继续...
$xml_file = "http://www.dailymotion.com/rss/user/dialhainaut/";
//$xml_file = "http://www.cs.washington.edu/research/xmldatasets/data/pir/psd7003.xml";
$fh = fopen($xml_file, "r");
if($fh){
$file_string = '';
$total_B = 0;
$max_B = 10485760;
//run through lines of the file, concatenating them into a string
while (!feof($fh)){
if($line = fgets($fh)){
$total_B += strlen($line);
if($total_B < $max_B){
$file_string .= $line;
} else {
break;
}
}
}
if($total_B < $max_B){
echo 'File ok. Total size = '.$total_B.' bytes. Proceeding...';
//proceed
$dom = new DOMDocument();
$dom->loadXML($file_string); //NOTE the method change because we're loading from a string
} else {
//reject
echo 'File too big! Max size = '.$max_B.' bytes.';
}
fclose($fh);
} else {
echo '404 file not found!';
}
关于php - 如果文件大于给定大小,则阻止从远程源加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36761377/