Heim  >  Artikel  >  Backend-Entwicklung  >  PHP获取(读取)本地文件与远程文件内容示例

PHP获取(读取)本地文件与远程文件内容示例

WBOY
WBOYOriginal
2016-07-25 08:54:281130Durchsuche
  1. $file = 'jbxue.com.php';
  2. //不支持远程
  3. $fso = fopen($file, 'r');
  4. echo $data = fread($fso, filesize($file));
  5. fclose($fso);
  6. ?>
复制代码

fopen() 将 file 指定的名字资源绑定到一个流上. filesize 返回文件大小的字节数,如果出错返回 FALSE. 注: 因为 PHP 的整数类型是有符号的,并且大多数平台使用 32 位整数,filesize() 函数在碰到大于 2GB 的文件时可能会返回非预期的结果.对于 2GB 到 4GB 之间的文件通常可以使用 sprintf("%u", filesize($file)) 来克服此问题. fread() 从文件指针 handle 读取最多 length 个字节. 该函数在读取完 length 个字节数,或到达 EOF 的时候,或(对于网络流)当一个包可用时就会停止读取文件,视乎先碰到哪种情况. 说明:低版本用法!建议php5用file_get_contents

例2,

  1. $file = 'jbxue.com.php';
  2. //支持远程
  3. $file = 'http://bbs.it-home.org';//
  4. echo $data = implode('', file($file));
  5. ?>
复制代码

file -- 把整个文件读入一个数组中 说明 读取二进制的文件

例3,

  1. $file = 'http://bbs.it-home.org';
  2. echo file_get_contents($file);
  3. ?>
复制代码

file_get_contents -- 将整个文件读入一个字符串 说明 string file_get_contents ( string filename [, int use_include_path [, resource context]]) 和 file() 一样,只除了 file_get_contents() 将文件返回为一个字符串. file_get_contents() 函数是用来将文件的内容读入到一个字符串中的首选方法.如果操作系统支持还会使用内存映射技术来增强性能.

以上分享了三例php获取远程文件的代码,希望对大家有所帮助。



Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn