file_get_contents()可读取文件或URL内容,但读取URL需开启allow_url_fopen,否则易失败;可通过stream_context_create()设置上下文发送POST请求或添加请求头;相比cURL,它使用简单但功能有限,适合简单任务,复杂场景推荐cURL。

file_get_contents()
PHP 中使用
file_get_contents()
$content = file_get_contents('your_file_or_url');解决方案:
<?php
// 从本地文件读取内容
$filename = 'example.txt';
$content = file_get_contents($filename);
if ($content !== false) {
echo "文件内容:\n" . $content;
} else {
echo "无法读取文件:$filename";
}
// 从 URL 读取内容 (确保 allow_url_fopen 已启用)
$url = 'https://www.example.com'; // 替换成你想读取的 URL
$url_content = @file_get_contents($url); // 使用 @ 抑制错误,因为网络请求可能失败
if ($url_content !== false) {
echo "\nURL 内容(部分):\n" . substr($url_content, 0, 200) . "..."; // 显示前 200 个字符
} else {
echo "\n无法读取 URL:$url";
}
// 使用上下文(Context)进行更高级的配置
$context_options = array(
'http' => array(
'method' => 'GET',
'header' => "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)\r\n", // 模拟浏览器
'timeout' => 10 // 设置超时时间
)
);
$context = stream_context_create($context_options);
$advanced_url_content = @file_get_contents($url, false, $context);
if ($advanced_url_content !== false) {
echo "\n高级 URL 内容(部分):\n" . substr($advanced_url_content, 0, 200) . "...";
} else {
echo "\n无法读取高级 URL:$url";
}
?>file_get_contents()
最常见的原因是 PHP 的
allow_url_fopen
立即学习“PHP免费学习笔记(深入)”;
解决办法是检查
php.ini
allow_url_fopen
On
@
try...catch
file_get_contents()
file_get_contents()
<?php
$url = 'https://www.example.com/api/endpoint';
$data = array('key1' => 'value1', 'key2' => 'value2');
$options = array(
'http' => array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result !== false) {
echo "POST 请求结果:\n" . $result;
} else {
echo "POST 请求失败";
}
?>这里,
http_build_query()
application/x-www-form-urlencoded
Content-type
Content-type
application/json
json_encode()
file_get_contents()
file_get_contents()
file_get_contents()
file_get_contents()
allow_url_fopen
cURL 的优点:
cURL 的缺点:
总的来说,如果只是简单的读取文件或 URL 内容,
file_get_contents()
file_get_contents()
以上就是PHP如何使用file_get_contents函数_PHP file_get_contents函数用法与实例解析的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号