Несколько сообщений PHP cUrl на одной странице - PullRequest
4 голосов
/ 06 декабря 2010

Таким образом, суть в том, что мне нужно отправить запрос данных XML на страницу шлюза, чтобы получить ответ XML, который O анализирует позже, к этому веб-сервису может быть от 3 до 60 запросов, к сожалению, мне нужно выполнить простой Зацикливайтесь прямо сейчас и делайте их по одному. Что касается ответа, мне понадобится только 1 (или максимум 5) строк в ответе, строка 2 - это первая строка, которая мне нужна, содержащая данные изображения. Поэтому я хотел бы иметь возможность выбирать, какие строки я читаю, если это вообще возможно.

Я создал простую функцию «Чтение», как я сказал из базового цикла for, вот код, который я сейчас использую и хотел бы пересмотреть.


$part1 = 'XML Beginning'; $part2 = XML End';
$posts = array( 0 => 'SC-010052214', 1 => 'SC-000032972', 2 => 'SC-012535460', 3 => 'SC-011257289', 4 => 'SC-010134078' );


 $ch = curl_init();

  curl_setopt($ch, CURLOPT_URL, 'http://example.com/index.php');
  curl_setopt($ch, CURLOPT_RETURNTRANSFER => 1);
  curl_setopt ($ch, CURLOPT_POST, 1);

 $count = count($posts);
 for($i=0;$i<$count;$i++) {

  curl_setopt ($ch, CURLOPT_POSTFIELDS, "payload=$part1{$posts[$i]}$part2");
  $return[] = curl_exec ($ch);

  }
 curl_close ($ch); 

print_r($return);

Ограничения: я не могу использовать? Post = $ data0 & post = $ data1 & post = $ data3, к сожалению, поэтому мне нужно лучшее решение. Кроме этого, я хотел бы посмотреть, какие улучшения можно сделать здесь.

Ответы [ 2 ]

1 голос
/ 06 декабря 2010

Может быть http://php.net/manual/en/function.curl-multi-init.php вам поможет

0 голосов
/ 06 декабря 2010

Из-за ограничений в быстром ответе,

<?php

function m_curl($input) {

        // compile queries for usable locations
        foreach($input['content'] as $pos=>$item) {
            $query = '<childDetailQuery><request><query-replacement>';
            $query .= "<item_number>{$item}</item_number>";

                    $query .= (isset($input['story']) && $input['story'] != NULL) 
                                ? "<story_type>".$input['story']."</story_type>"
                                : '<story_type>SHORT</story_type>';

                    $query .= (isset($input['party']) && $input['party'] != NULL) 
                                ? "<party_number>".$input['party']."</party_number>"
                                : '';

            $query .= "</query-replacement><latency-tolerance>NONE</latency-tolerance>";
            $query .= '</request></childDetailQuery>';

        $queries[] = $query;
                unset($query);
        }


        // make sure the rolling window isn't greater than the # of urls
        $limit = 10;
        $limit = (sizeof($queries) < $limit) ? sizeof($queries) : $limit;

        $master = curl_multi_init();
        $curl_arr = array();

            // add additional curl options here
            $std_options = array(
                CURLOPT_RETURNTRANSFER => 1,
                CURLOPT_FOLLOWLOCATION => 1,
                CURLOPT_MAXREDIRS => 0,
            );

        $options = ($coptions) ? ($std_options + $coptions) : $std_options;

        echo $input['location'];
        // start the first batch of requests
        for ($i = 0; $i < $limit; $i++) {
            $ch = curl_init();

                $options[CURLOPT_POSTFIELDS] = "payload=".$queries[$i];

            curl_setopt_array($ch,$options);
            curl_multi_add_handle($master, $ch);
        }

        do {
            while(($execrun = curl_multi_exec($master, $running)) == CURLM_CALL_MULTI_PERFORM);
                if($execrun != CURLM_OK) {
                                    echo 'Curl Error'; break;
                }


            // a request was just completed -- find out which one
            while($done = curl_multi_info_read($master)) {
                $info = curl_getinfo($done['handle']);
                if ($info['http_code'] == 200)  {
                    $output = curl_multi_getcontent($done['handle']);

                    // request successful.  process output using the callback function.
                    parse_returns($output);

                    // start a new request (it's important to do this before removing the old one)
                    $ch = curl_init();
                    $options[CURLOPT_POSTFIELDS] = "payload=".$queries[$i++];  // increment i
                    curl_setopt_array($ch,$options);
                    curl_multi_add_handle($master, $ch);

                    // remove the curl handle that just completed
                    curl_multi_remove_handle($master, $done['handle']);

                } else {

                    echo 'Failed on:'; var_dump($info);
                    echo 'With options:'; var_dump($options);

                    // request failed.  add error handling.
                }
            }
        } while ($running);

        curl_multi_close($master);
        return false;
}

function parse_returns($data) {
    print_r($data);
}

// set query numbers
$data = array(
    0 => 'SC-010052214',
    1 => 'SC-000032972',
    2 => 'SC-012535460',
    3 => 'SC-011257289',
    4 => 'SC-010134078'
);

// set options array
$options = array(
    'location'      => 'http://ibudev.wvus.org/websvc/actions/wvsMessageRouter.php',
    'readline'      => 2,
    'coptions'      => NULL,
    'content'       => $data,
    'story'         => 'FULL',
    'party'         => NULL,
);


m_curl($options);

?>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...