【问题标题】:Web scraping to JSON/array网页抓取到 JSON/数组
【发布时间】:2020-12-05 01:56:27
【问题描述】:

我在网页抓取方面遇到问题。这是我要抓取的链接:

https://www.indopremier.com/module/saham/include/data-brokersummary.php?code=BBCA&start=11/30/2020&end=11/30/2020&fd=all&board=RG

我只想获取 B.lot 和 S.lot 上的数据,以便对数据求和。 我设法获取了表信息,因为该链接上的返回数据是 HTML,但我仍然混淆将数据放在数组中以便我可以求和。

<?php    
function tdrows($elements) {
   $str = "";
   foreach ($elements as $element) {
      $str .= $element->nodeValue ;
   }
   return $str;
}
    
function getdata() {
   $contents = file_get_contents('https://www.indopremier.com/module/saham/include/data-brokersummary.php?code=BBCA&start=11/30/2020&end=11/30/2020&fd=all&board=RG');
   $DOM = new DOMDocument;
   $DOM->loadHTML($contents);
   $items = $DOM->getElementsByTagName('tr');
   foreach ($items as $node) {
      $list[] = tdrows($node->childNodes);
   }    
}
getdata();
?>

【问题讨论】:

标签: php


【解决方案1】:

接下来的代码解析 HTML 并返回数据数组。在此之后,您可以使用常规数组函数汇总数据:

<?php
function tdrows($elements)
{
    $row_data = [];
    foreach ($elements as $element) {
        $value = $element->firstChild->nodeValue;
        if ($value) {
            $row_data[] = trim($value);
        }
    }

    return $row_data;
}

function getdata()
{
    $contents = file_get_contents(
        "https://www.indopremier.com/module/saham/include/data-brokersummary.php?code=BBCA&start=11/30/2020&end=11/30/2020&fd=all&board=RG"
    );
    $DOM = new DOMDocument();
    $DOM->loadHTML($contents);

    $items = $DOM->getElementsByTagName("tr");

    foreach ($items as $node) {
        $list[] = tdrows($node->childNodes);
    }

    return $list;
}

$result = getdata();

var_export($result);

Share PHP code

【讨论】:

    猜你喜欢
    • 2018-12-13
    • 2021-08-29
    • 2018-04-02
    • 1970-01-01
    • 2020-02-24
    • 2019-11-10
    • 1970-01-01
    • 2020-06-18
    相关资源
    最近更新 更多