foreach循环没有给出所需的结果

时间:2015-03-28 17:51:53

标签: php curl

我正在使用PHP的cURL库执行API请求。输出为XML,如下所示:

<xml>
   <urlnext>
    <list>
      <list1>
      <list2>
      <list3>

获得此输出后,我使用cURL再次调用urlnext内的网址并获得类似的输出,依此类推,如果我继续获取urlnext作为响应我们称之为带有cURL库的新URL。

但是那个循环正在调用第一个响应urlnext,而不是下一个响应。它会对第一个urlnext做出回复,但它不会进行下一个循环。请告诉我如何修改此循环。这是我的代码:

$dat1 = httpGet($url);
$xml2 = new SimpleXMLElement($dat1);

foreach ($xml2 as $array) {
    $url  = $array->urlnext;
    $data = httpGet($url);
    $xml2 = new SimpleXMLElement($data);

    foreach ($xml2 as $array) {
        doing the operations.....
    }
}

httpGet函数正在执行cURL请求并按预期返回XML。

<?php

function getData($url){
   // $dat1=httpGet($url);
$ch = curl_init();  

    curl_setopt($ch,CURLOPT_URL,$url);
 curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
//  curl_setopt($ch,CURLOPT_HEADER, false); 
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'header1: value1',
    'header1:value2'
    )); 
    $output=curl_exec($ch); 
    curl_close($ch);
   //return $output;

    return new SimpleXMLElement($output);
}

//Create main array that will contain the XML responses of all the urls.
$mainData = Array();

//Pass in URL, calls getData function, finds next url, then calls its self with the new URL.  Be forewarned--- this could create an infinite loop
function loopData($url){
    $data = getData($url);
    array_push($mainData, $data);

    foreach($data as $array){
        $nexturl=$array->urlnext;
        loopData($nexturl);
    }
}
//Call initial URL
$url = "http://exampleurl.com";
loopData($url);

//Print all data results.
print_r($mainData);
?>

1 个答案:

答案 0 :(得分:0)

立即跳出来的一件事就是缺少&#34; $&#34;在&#34;数据之前#34;第6行的变量。但共享变量名也是有关的。

如果不知道您正在调用的API,我无法对此进行测试,但这是我最初创建的代码片段,可以执行您所描述的内容:

//Pass in URL to call, returns the XML element  
function getData($url){
    $dat1=httpGet($url);
    return new SimpleXMLElement($dat1);
}

//Create main array that will contain the XML responses of all the urls.
$mainData = Array();

//Pass in URL, calls getData function, finds next url, then calls its self with the new URL.  Be forewarned--- this could create an infinite loop
function loopData($url){
    $data = getData($url);
    array_push($mainData, $data);
    foreach($data as $array){
        $nexturl=$array->urlnext;
        loopData($nexturl);
    }
}
//Call initial URL
$url = "http://www.exampleurl.com";
loopData($url);

//Print all data results.
print_r($mainData);