Php 从txt文件提取到数组中?
我想从文本文件中获取代理,然后将它们添加到我的数组中。我尝试了以下代码,但它无法获取代理Php 从txt文件提取到数组中?,php,Php,我想从文本文件中获取代理,然后将它们添加到我的数组中。我尝试了以下代码,但它无法获取代理 $path = './proxies.txt'; $proxies = array(); foreach(file($path, FILE_SKIP_EMPTY_LINES) as $line) { $proxy = trim($line); list($ip, $port) = explode(':', $proxy); $proxies[$ip] = $port; } var_dump($prox
$path = './proxies.txt';
$proxies = array();
foreach(file($path, FILE_SKIP_EMPTY_LINES) as $line) {
$proxy = trim($line);
list($ip, $port) = explode(':', $proxy);
$proxies[$ip] = $port;
}
var_dump($proxies);
然后从数组中获取代理并使用
curl_setopt($ch, CURLOPT_PROXY,$proxies[array_rand($proxies)]);
部分代码:
$path = './proxies.txt';
$proxies = array();
foreach(file($path, FILE_SKIP_EMPTY_LINES) as $line) {
$proxy = trim($line);
list($ip, $port) = explode(':', $proxy);
$proxies[$ip] = $port;
}
var_dump($proxies);
$ch = curl_init('https://www.website.com');
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_PROXY, $proxy);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,0);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT,15);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_HTTP_VERSION,'CURL_HTTP_VERSION_1_1' );
curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
curl_setopt($ch, CURLOPT_ENCODING , "gzip,deflate");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_PROXY, $proxy);
curl_setopt($ch, CURLOPT_PROXY, $proxy_ip);
curl_setopt($ch, CURLOPT_REFERER, $refer);
curl_setopt($ch, CURLOPT_USERAGENT,$agents[array_rand($agents)]);
curl_setopt($ch, CURLOPT_PROXY,$proxies[array_rand($proxies)]);
curl_setopt($ch, CURLOPT_COOKIEFILE, dirname(__FILE__).'/cookie.txt');
curl_setopt($ch, CURLOPT_COOKIEJAR, dirname(__FILE__).'/cookie.txt');
我找到的最快方法是:
根据您设置文本文件的方式,您可能需要
使用\n位进行播放
在这里找到解决方案:你看过了吗:发布你的文件的一些示例文本@Ashish i sample code添加此代码使我的脚本无法打开,收到白页…@bamba92你修改了你文件的url了吗?您应该使用
$handle=fopen(“./proxies.txt”,“r”)代码>当然了,但我还是得到了白页@bamba92我忘了一个代码>在第2行,我编辑了我的答案。此外,请将注释//打开文件时出错。
更改为echo“错误:无法打开文件。”代码>并再次尝试脚本打开,现在就可以了。。。。。但由于某些原因,代理无法获取。。。。。。。。。2天处理这个问题,我希望你能帮上忙。。。。。。。。
// Open the file $fp = @fopen($filename, 'r');
>
> // Add each line to an array if ($fp) { $array = explode("\n",
> fread($fp, filesize($filename))); } where $filename is going to be the
> path & name of your file, eg. ../filename.txt.
>
$handle = fopen("proxies.txt", "r");
$proxies = array();
if ($handle) {
while (($line = fgets($handle)) !== false) {
$proxies[explode(':', $line)[0]] = explode(':', $line)[1];
}
} else {
// error opening the file.
echo "Error: unable to open the file.";
}
fclose($handle);