【问题标题】:Extract specific data from website using php使用php从网站中提取特定数据
【发布时间】:2017-06-29 16:44:03
【问题描述】:

我想从某个网站获取数据。 部分Html如下:

<span class="last">10,750.00</span>

我想退出 10750 不带逗号和点。

数字 10,750.00 只是一个例子。这个数字正在改变

【问题讨论】:

  • 如果你知道它是 10,750.00 为什么你需要提取它?
  • 除非您可以访问同一服务器上的页面
  • 您可以使用 file_get_contents() 下载 HTML,然后使用正则表达式查找值 regex101.com/r/efBIbq/1,最后执行 str_replace 删除点和逗号。然而,HTML 上的正则表达式有时可能会出现问题。如果它是一个小的 HTML 文件,它可能工作正常

标签: php extract


【解决方案1】:

从此开始:

<span class="last">anything here</span>

你可以这样做:

$page = file_get_contents('http://www.example.com/');
$toSearch1 = '<span class="last">';
$toSearch2 = '</span>';

获取内容并准备搜索变量

$page = strstr($page, $toSearch1);
$page = strstr($page, $toSearch2, true);

这将只提取“任何内容”并删除其他不必要的 HTML

然后:

$page = strip_tags($page);

这将删除 HTML 标记,或者,如果您想手动尝试

$page = str_replace($toSearch1, "", $page);
$page = str_replace($toSearch1, "", $page);

终于

$page = str_replace(['.', ','], '' , $page);

删除点和逗号

$page = substr($page, 0, -2);

去掉小数

$page = (int)$page;

你可以强制转换为int,即使PHP会自动处理如果你使用数字进行计算

在这里摆弄 ==> https://www.tehplayground.com/oqywfzmo2IWJdN0C

【讨论】:

  • 数字 10,750.00 只是一个例子。数字在变化。我想捕获它以在某些方程式中使用它
  • 我得到空白页。我没有看到任何回声
  • 我怎样才能去掉逗号和点看起来像这样:10750
  • 对不起,我不懒只是这样一个新手:)
  • 如果你接受这个答案就好了!谢谢。你可以在这里找到方法 ==> stackoverflow.com/help/someone-answers
【解决方案2】:

如果变量中有 HTML 部分,则可以这样做:

$html = '<span class="last">10,750.00</span>';
$without_tag = strip_tags($html); // Remove Tags HTML
$number_float = (float) str_replace(',', '', $without_tag); // Remove commas and change to float
echo $number_float; // 10750

如果您没有可以使用的 HTML:

$html = file_get_contents("http://example.com/");
$part = stristr(stristr($html, '<span class="last">'), '</span>', true);
$without_tag = strip_tags($part); // Remove Tags HTML
$number_float = (float) str_replace(',', '', $without_tag); // Remove commas and change to float
echo $number_float; // 10750

【讨论】:

  • 数字 10,750.00 只是一个例子。数字在变化。我想捕获它以在某些方程式中使用它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-04-18
  • 1970-01-01
  • 2012-07-19
  • 2013-01-06
  • 2021-11-03
  • 2016-01-11
  • 2015-06-09
相关资源
最近更新 更多