从不同的网址获取数据

时间:2014-11-19 21:13:37

标签: php

我是php的新手,我想获取许多数据并从不同的网址输出它们,所以实际上我创建了一个可以工作并获取一个数据..到目前为止,我已经搜索过并且看了这么多...但我无法&#39 ; t计算如何获得倍数..

所以要考虑一件事:我突出显示的黄色文字超过100个...我的意思是eid = 1到eid = 102 ..每个都有数据存储在其中。

enter image description here

我的PHP代码就是这个

<?php

    $eType=2;
    $eId=43;
    $lType=1;
    $dNames=drivername;
    $shard="Apex";
    $session = curl_init();


    curl_setopt ($session, CURLOPT_URL, "http://world.needforspeed.com/SpeedAPI/ws/game/nfsw/leaderboards?output=xml");
    curl_setopt ($session, CURLOPT_POST, true);
    curl_setopt ($session, CURLOPT_POSTFIELDS, "et=".$eType."&eid=".$eId."&lt=".$lType."&dn=".$dNames."&shard=".$shard);
    curl_setopt ($session, CURLOPT_HEADER, true);
    curl_setopt ($session, CURLOPT_RETURNTRANSFER, true);


    $response = curl_exec($session);
    curl_close($session);


    // Get the XML from the response, bypassing the header

    if (!($xml = strstr($response, '<?xml'))) {
        $xml = null;
    }

    // Output the XML

    $worldLeaderboard = simplexml_load_string($xml);

    foreach ($worldLeaderboard->worldLeaderboard as $world){
        $rank     = $world['rank'];
        $name     = $world['personaName'];
        $car      = $world['make'];
        $model    = $world['carName'];
        $duration = $world['eventDuration'];

    echo <<<EOD
    $rank $name $car $model $duration
    EOD;

    }

?>

因为你可以看到我的代码,它工作得很好并从那些数据输出..我知道我可以做多次通过处理所有代码并粘贴100次,并更改每个$ eid变量值但是那个&#39; s我假设太多和数据消耗..

2 个答案:

答案 0 :(得分:0)

为curl调用创建一个函数,将URL放在一个数组中并循环遍历数组,并使用你编写的curl函数中数组中的每个条目。

function my_curl_function($url)
{
    // curl call
    return $result;
}

$urls[] = 'url1';
$urls[] = 'url2';
$urls[] = 'url3';
// etc

foreach($urls AS $url)
{
    echo my_curl_function($url);
}

答案 1 :(得分:0)

您可以使用简单的&#39; for&#39;循环。

for($eId=1;$eId<=102;$eId++) {
    $eType=2;
    $lType=1;
    $dNames=drivername;
    $shard="Apex";
    $session = curl_init();


    curl_setopt ($session, CURLOPT_URL, "http://world.needforspeed.com/SpeedAPI/ws/game/nfsw/leaderboards?output=xml");
    curl_setopt ($session, CURLOPT_POST, true);
    curl_setopt ($session, CURLOPT_POSTFIELDS, "et=".$eType."&eid=".$eId."&lt=".$lType."&dn=".$dNames."&shard=".$shard);
    curl_setopt ($session, CURLOPT_HEADER, true);
    curl_setopt ($session, CURLOPT_RETURNTRANSFER, true);


    $response = curl_exec($session);
    curl_close($session);


    // Get the XML from the response, bypassing the header

    if (!($xml = strstr($response, '<?xml'))) {
        $xml = null;
    }

    // Output the XML

    $worldLeaderboard = simplexml_load_string($xml);

    foreach ($worldLeaderboard->worldLeaderboard as $world){
        $rank     = $world['rank'];
        $name     = $world['personaName'];
        $car      = $world['make'];
        $model    = $world['carName'];
        $duration = $world['eventDuration'];

echo <<<EOD
$rank $name $car $model $duration
EOD;
    }
}