0

我正在从远程网站提取数据,我需要获取每个表列中的数据。

这是数据示例

<tr>
    <td><a href="https://www.example.com/graphs/fruit-bonanza-fruit-betsafe.html" title="Fruit Bonanza: Fruit (Betsafe)">Bonanza: Fruit (B'safe)</a></td>
    <td sorttable_customkey="-48">&pound;30</td>
    <td sorttable_customkey="-128">&pound;80</td>
    <td sorttable_customkey="333331" style="background-color:#f0dd66; font-weight:bold;">3d, 20h</td>
    <td sorttable_customkey="-1541574886" style="background-color:#f0dd66; font-weight:bold;">128d, 2h ago</td>
    <td sorttable_customkey="-94">94<strong>&deg;</strong></td>
    <td sorttable_customkey="-500"><img src="https://www.example.com/imgs/green-check-small.gif"/></td>
    <td sorttable_customkey="-894">Maybe</td>
    </tr>

但是 sorttable_customkey 值在每个实例中都不同,所以我不知道该怎么做。我不得不从标签内部获取数据,因为页面上还有我不想要的其他元素。

这是我提取初始表数据的代码

$sample = file_get_contents('data/15-03-2019.php');
function getContents($str, $startDelimiter, $endDelimiter) {
  $contents = array();
  $startDelimiterLength = strlen($startDelimiter);
  $endDelimiterLength = strlen($endDelimiter);
  $startFrom = $contentStart = $contentEnd = 0;
  while (false !== ($contentStart = strpos($str, $startDelimiter, $startFrom))) {
    $contentStart += $startDelimiterLength;
    $contentEnd = strpos($str, $endDelimiter, $contentStart);
    if (false === $contentEnd) {
      break;
    }
    $contents[] = substr($str, $contentStart, $contentEnd - $contentStart);
    $startFrom = $contentEnd + $endDelimiterLength;
  }
  return $contents;
}

$array = getContents($sample, '<tbody>', '</tbody>');
  foreach($array as $link )
   {
    $removetr = str_replace('<tr>','',$link);
    $replacetr = str_replace('</tr>','<br>',$link);
    $removetd = str_replace('<td>','',$removetr);
    $replacetd = str_replace('</td>',',',$removetd);
    echo $link;
   }

我尝试执行一系列 str_replace 来删除标签并用逗号替换,</td>但是由于可排序自定义键的值不同(在页面下方一直是唯一的),不用说替换不工作我的最终结果是我试图获取每列中的所有数据并有效地创建一个 CSV 以便可以导入数据</tr>< br>

努力解释我想要做什么(希望有人能理解我想说的话)

4

2 回答 2

0

不要浪费时间自己编写网络爬虫......使用现成的解决方案,例如这个https://github.com/FriendsOfPHP/Goutte或更简单的这个https://symfony.com/doc/current/components /dom_crawler.html

于 2019-03-15T10:57:51.837 回答
0

刚刚意识到我可以使用

preg_replace('/<td (.*?)>(.*?)<\/td>/', '$2,', $str);

并使用多个通配符,然后将第二个实例中的数据插入到我想要的位置

于 2019-03-15T10:59:44.647 回答