【问题标题】:running curl pulling rows sequentially in a loop运行 curl 在循环中按顺序拉行
【发布时间】:2021-05-29 12:16:02
【问题描述】:

在 id.txt 中

詹妮弗:约翰
罗伯特:威廉
琳达:丹尼尔
伊丽莎白:托马斯

$variable = explode("\n", file_get_contents('id.txt'));
$explode = explode(":", $variable[array_rand($variable)]);


curl_setopt_array($curl, array(
  CURLOPT_URL => 'https://www.questions.com/api/',
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'POST',
  CURLOPT_POSTFIELDS =>'{
    "source": 4
}',
  CURLOPT_HTTPHEADER => array(
    'CH-Languages: en-US',
    'CH-UserNAME: '.$explode[0].'',
    'CH-UserSURNAME: Token '.$explode[1].''
  ),
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;

我想按顺序循环运行每一行 我该怎么做??

  1. 詹妮弗:约翰线
  2. 线罗伯特:威廉

【问题讨论】:

    标签: php explode


    【解决方案1】:

    如果您想按顺序迭代数组,请不要使用array_rand。为此目的使用foreach

    这应该可行

    ## be careful about line breaks. There could be more \r, \n, \r\n
    ## I would do explode("\n", str_replace(["\r", "\n", "\r\n"], "\n", file_get_contents('id.txt')))
    
    ## CURLOPT_USERAGENT -> set if required
    ## CURLOPT_POST -> generally this is preferred over CURLOPT_CUSTOMREQUEST
    
    $variable = explode("\n", file_get_contents('id.txt'));
    foreach ($variable as $line) {
        $curl = curl_init();    ## Depending on the usage you can move this and curl_close outside the loop
        $explode = explode(":", $line);
        curl_setopt_array($curl, array(
            CURLOPT_URL => 'https://www.questions.com/api/',
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => '{"source": 4}',  # use json_encode to get proper json strings.
            CURLOPT_HTTPHEADER => array(
                'CH-Languages: en-US',
                'CH-UserNAME: ' . $explode[0] . '',
                'CH-UserSURNAME: Token ' . $explode[1] . ''
            ),
        ));
    
        $response = curl_exec($curl);
        # $error = curl_error($curl);  # check to see if there are any errors
        # $curlInfo = curl_getinfo($curl);   # an array with more information about the request
    
        curl_close($curl);
        echo $response;
    }
    
    

    【讨论】:

    • 但是它运行一行并且循环停止。不是一条一条跑完所有的线吗?
    • 编辑了答案以包含curl_init()
    • 很高兴它成功了。由于您是新用户,请阅读此内容-> stackoverflow.com/help/someone-answers
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-21
    • 1970-01-01
    • 2022-01-11
    • 1970-01-01
    • 2022-07-26
    • 1970-01-01
    相关资源
    最近更新 更多