php中的foreach循环获取提供的无效参数

时间:2011-06-26 00:19:00

标签: php loops foreach

使用以下代码时,我收到“提供的参数无效”。我可以成功解析一个IP地址和端口号,但我不知道如何一次获得多个。我的foreach循环不起作用。有什么想法吗?

$dom = new DOMDocument();
$dom->loadHTMLFile($url);
$xml = simplexml_import_dom($dom);
$dom_results = $xml->xpath("/html/body/div[@id='subpagebgtabs']/div[@id='container']/table[@id='listtable']");

$ip_address = $dom_results[0]->tr->td[1]->span;
$ip_post = $dom_results[0]->tr->td[2];

$address_parts = $ip_address.":".$ip_post;

foreach ($address_parts as $address_full){
    echo $address_full . "<br>";
}

$ Dom_Results输出

["tr"]=>
    array(50) {
      [0]=>
      object(SimpleXMLElement)#5 (3) {
        ["@attributes"]=>
        array(2) {
          ["class"]=>
          string(0) ""
          ["rel"]=>
          string(7) "9054676"
        }
        ["comment"]=>
        object(SimpleXMLElement)#56 (0) {
        }
        ["td"]=>
        array(8) {
          [0]=>
          object(SimpleXMLElement)#57 (2) {
            ["@attributes"]=>
            array(2) {
              ["class"]=>
              string(20) "leftborder timestamp"
              ["rel"]=>
              string(10) "1309047901"
            }
            ["span"]=>
            string(10) "2 minutes"
          }
          [1]=>
          object(SimpleXMLElement)#58 (1) {
            ["span"]=>
            string(13) "122.72.10.201"
          }
          [2]=>
          string(3) "80"

2 个答案:

答案 0 :(得分:0)

我认为这就是你要找的东西:

// If results are found
if ( ! empty($dom_results) )
  // Loop through each result. Based on your XPath query, the $dom_results
  // contains tables. This loops through the rows of the first table.
  foreach ( $dom_results[0]->tr as $row )
  {
    $ip_address = $row->td[1]->span;
    $ip_post = $row->td[2];

    // Output the address
    echo $ip_address . ":" . $ip_post . "<br />";
  }

答案 1 :(得分:0)

似乎你想要提取所有的IP地址和端口号,并像

那样连接它

ipaddress:port

所以试试这个

foreach($dom_results as $dom) {
  $ip = $dom->tr->td[1]->span;
  $port = $dom->tr->td[2];
  $address = $ip . ":". $port;
  echo $address . "<br />";
}