如何合并2个PHP脚本输出的结果

时间:2014-04-06 12:20:36

标签: php curl

我只得到第一个脚本的结果。但我希望两个PHP脚本的响应都在一个输出中。在我正在开发的程序中,我正在查询几个远程服务器。我必须在不同的服务器上搜索信息,并在一个响应中返回结果。

<?php
    // build the individual requests as above, but do not execute them
    $ch_1 = curl_init('http://lifesaver.netai.net/example/pharm.php');
    $ch_2 = curl_init('http://192.168.1.2/example/pharm.php');
    curl_setopt($ch_1, CURLOPT_RETURNTRANSFER, false);
    curl_setopt($ch_2, CURLOPT_RETURNTRANSFER, false);
    curl_setopt($ch_1, CURLOPT_POST,1);
    curl_setopt($ch_2, CURLOPT_POST,1);
    curl_setopt($ch_1, CURLOPT_POSTFIELDS, "name=$value");
    curl_setopt($ch_2, CURLOPT_POSTFIELDS, "name=$value");

    // $_POST["name"]

    // build the multi-curl handle, adding both $ch
    $mh = curl_multi_init();
    curl_multi_add_handle($mh, $ch_1);
    curl_multi_add_handle($mh, $ch_2);

    // execute all queries simultaneously, and continue when all are complete
    $running = null;
    do {
      curl_multi_exec($mh, $running);
    } while ($running);

    // all of our requests are done, we can now access the results
    $response_1 = curl_multi_getcontent($ch_1);
    $response_2 = curl_multi_getcontent($ch_2);

    echo $response_1;
    echo $response_2;
?>

1 个答案:

答案 0 :(得分:0)

根据curl_multi_getcontent的文档,您需要将CURLOPT_RETURNTRANSFER设置为true而不是false

此外,curl_multi_init的文档显示了一个与执行循环相比略有不同的示例:

//execute the handles
$running = null;
do {
    $mrc = curl_multi_exec($mh, $running);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);

while ($running && $mrc == CURLM_OK) {
    if (curl_multi_select($mh) != -1) {
        do {
            $mrc = curl_multi_exec($mh, $running);
        } while ($mrc == CURLM_CALL_MULTI_PERFORM);
    }
}

你可以这样试试。