循环遍历数组值

时间:2014-03-31 08:22:37

标签: php arrays loops

我有一个小问题:

我需要重复这个

do {
    $QUERY = "/member?id=".$counter."&action=refresh";
    $URL = $HTTP.$HTTPUSER.":".$HTTPPASS."@".$HTTPSERVER.":".$HTTPPORT.$QUERY;
    $xml = file_get_contents($URL);

    $data = new SimpleXMLElement($xml);

    $test_ip = (string)$data->c1;

    $dnsip = explode('<br>', $test_ip);

    $ext_ip = strip_tags($dnsip[1]);

    if ($ext_ip != "127.0.0.1" && $ext_ip != "localhost") {

        $dns = strip_tags($dnsip[0]);

        echo "$dns $ext_ip <br>";
    }

    $counter +=1;

} while (!empty($data));

与数组中的值一样多次,所以我尝试添加此

    $ports  = array('2001','2002','2003'); 

foreach ($ports as $HTTPPORT) {

echo "$HTTPPORT<br>";

$counter = 1;

do {
    $QUERY = "/member?id=".$counter."&action=refresh";
    $URL = $HTTP.$HTTPUSER.":".$HTTPPASS."@".$HTTPSERVER.":".$HTTPPORT.$QUERY;
    $xml = file_get_contents($URL);

    $data = new SimpleXMLElement($xml);

    $test_ip = (string)$data->c1;

    $dnsip = explode('<br>', $test_ip);

    $ext_ip = strip_tags($dnsip[1]);

    if ($ext_ip != "127.0.0.1" && $ext_ip != "localhost") {

        $dns = strip_tags($dnsip[0]);

        echo "$dns $ext_ip <br>";
    }

    $counter +=1;

} while (!empty($data)); }

问题是它只使用第一个端口号(2001)执行脚本,我无法发现原因。

任何想法?

1 个答案:

答案 0 :(得分:1)

你可能会在你的内部得到一个例外......而且&#39;引起麻烦的循环。

我添加了一个&#39;尝试..抓住&#39;阻止和一些回声&#39;声明,以确保它始终循环所有的端口&#39;现在。改变了#catch;#39;将$ data标记为空,然后继续。

这里是经过测试的代码:

<?php

$ports  = array('2001','2002','2003');

$counter = 0; // total count of documents

foreach($ports as $HTTPPORT) {

    echo $HTTPPORT, ' start of process port loop<br/>';

    try { // catch any error -- report it and loop round again
        do {
            $QUERY = "/member?id=".$counter."&action=refresh";
            $URL = ''; // $HTTP.$HTTPUSER.":".$HTTPPASS."@".$HTTPSERVER.":".$HTTPPORT.$QUERY;
            try {
                $xml = file_get_contents($URL);
                $data = new SimpleXMLElement($xml);
            }
            catch (Exception $e) { // ignore any errors
                echo 'SimpleXMLElement : oops :', $e->getMessage(), '<br />';
                $data = ''; // mark as empty
            }

            if (!empty($data)) { // process data
                $test_ip = (string)$data->c1;
                $dnsip = explode('<br>', $test_ip);

                $ext_ip = strip_tags($dnsip[1]);

                if ($ext_ip != "127.0.0.1" && $ext_ip != "localhost") {

                    $dns = strip_tags($dnsip[0]);

                    echo "$dns $ext_ip <br>";
                }
            }

            $counter +=1;

        } while (!empty($data));

    } // end of try to get and process a document...
    catch (Exception $e) { // catch all errors for now
        echo 'Processing List of Ports: oops! :', $e->getMessage(), '<br />';
    }
} // end of foreach port