复制
| function saveImageFromUrl($url, $savePath) { |
| |
| $imageContent = file_get_contents($url); |
| |
| |
| file_put_contents($savePath, $imageContent); |
| } |
| |
| |
| $url = 'https://example.com/image.jpg'; |
| $savePath = '/path/to/save/image.jpg'; |
| saveImageFromUrl($url, $savePath); |
复制
请注意,上述代码依赖于allow_url_fopen
选项启用。如果 allow_url_fopen
被禁用或不适用于你的环境,请尝试使用 cURL 函数来替代上述代码:
| function saveImageFromUrl($url, $savePath) { |
| $ch = curl_init($url); |
| $fp = fopen($savePath, 'wb'); |
| |
| curl_setopt($ch, CURLOPT_FILE, $fp); |
| curl_setopt($ch, CURLOPT_HEADER, 0); |
| |
| curl_exec($ch); |
| curl_close($ch); |
| fclose($fp); |
| } |
| |
| $url = 'https://example.com/image.jpg'; |
| $savePath = '/path/to/save/image.jpg'; |
| saveImageFromUrl($url, $savePath); |
复制
这段代码使用 cURL 执行远程请求,并将响应内容写入本地文件。