【问题标题】:Adding up integers from extracted data将提取的数据中的整数相加
【发布时间】:2014-08-26 06:59:28
【问题描述】:

我有一个从网站中提取整数值的代码。我想知道我是否可以将所有这些整数相加并显示总和。

<?php
header('Content-Type: text/html; charset=utf-8');
$grep = new DoMDocument();
@$grep->loadHTMLFile("http://www.lelong.com.my/Auc/List/BrowseAll.asp");

$finder = new DomXPath($grep);
$class = "CatLevel1";
$nodes = $finder->query("//*[contains(@class, '$class')]");

foreach ($nodes as $node) {
    $span = $node->childNodes;
    echo str_replace(array('(', ')'), '', $span->item(1)->nodeValue);
    echo '<br/>';
}    
?>

期望的输出: 9768 9321 11407 31611 36506

总数:345664

谢谢!

【问题讨论】:

    标签: php html xpath web-scraping domdocument


    【解决方案1】:

    只需像普通变量一样将其相加即可。在顶部初始化零。示例:

    $total = 0;
    foreach ($nodes as $node) {
        $span = $node->childNodes;
        $number = preg_replace("/[^0-9]/", '', $span->item(1)->nodeValue);
        echo '<br/>';
    
        $total += (int) $number;
    }
    
    echo "Total: $total";
    

    【讨论】:

      【解决方案2】:

      您可以简单地将整数分配给一个变量,并在foreach 的每次迭代中添加它们

      $total = 0;
      foreach ($nodes as $node) {
          $span = $node->childNodes;
          echo str_replace(array('(', ')'), '', $span->item(1)->nodeValue);
          $total += $span->item(1)->nodeValue;
          echo '<br/>';
      }
      echo "Total: ".$total;
      

      更新:确保您在$span-&gt;item(1)-&gt;nodeValue) 中得到的是整数而不是字符串。您可以将$total += $span-&gt;item(1)-&gt;nodeValue; 修改为$total += intval($span-&gt;item(1)-&gt;nodeValue); 以将返回的字符串(如“97”)转换为int 97。

      【讨论】:

        【解决方案3】:

        看起来你的代码完成了你想做的 90% 的事情,相比之下,整数的相加应该相对简单。

        假设这部分返回你的整数:

        foreach ($nodes as $node) {
            $span = $node->childNodes;
            echo str_replace(array('(', ')'), '', $span->item(1)->nodeValue);
            echo '<br/>';
        } 
        

        改成这样:

        $total = 0;
        foreach ($nodes as $node) {
            $span = $node->childNodes;
            $integer = str_replace(array('(', ')'), '', $span->item(1)->nodeValue);
            $total += $integer;
            echo "$integer<br/>";
        } 
        echo "Total: $total";
        

        【讨论】:

          猜你喜欢
          • 2022-11-19
          • 2018-05-13
          • 1970-01-01
          • 2019-08-12
          • 2015-05-28
          • 1970-01-01
          • 1970-01-01
          • 2012-05-27
          • 2019-04-10
          相关资源
          最近更新 更多