【问题标题】:PHP simple html dom, selecting just a part of the contentPHP简单的html dom,只选择一部分内容
【发布时间】:2020-08-26 02:27:57
【问题描述】:

我使用简单的 html dom 来解析 html。 https://simplehtmldom.sourceforge.io/

给定以下代码

<div class="item-price offer-price price-tc default-price">
$129.990
<span class="discount-2">-35%</span>
</div>

如何只选择价格? 我使用$html-&gt;find(div.offer-price, 0)-&gt;plaintext;,但它也选择了跨度的内容。

【问题讨论】:

  • 我不确定您正在使用的库,但在适当的 DOM 中,DIV 将有一个子节点列表,包括文本节点。 DIV 的第一个子节点就是你想要的。
  • “我正在使用简单的 html dom” 欢迎来到有史以来最糟糕的 PHP DOM 库之一。查看链接副本中的列表
  • Ricardo,PHP 具有出色的 DOM 实现以及 XPath。以下是我将如何使用内置库的方法。 pastebin.com/8SrB62SB希望你能把它翻译成你正在使用的库,或者只是将你的代码转换成 PHP 的内置功能。
  • 另外,FWIW,我认为这个问题不应该结束。或者至少不会作为“如何使用 PHP 解析 html”的副本而关闭。这更多的是关于理解 DOM 的问题,而不是理解如何用 PHP 获得 DOM 表示。 ¯_(ツ)_/¯ 我已经投票决定重新开放。
  • 感谢@JAAulde,您的 cmets 真的很有帮助。

标签: php web-crawler simple-html-dom


【解决方案1】:

不知道在simplehtmldom中怎么做,但是你可以使用DOMDocument + DOMXPath来提取它,

<?php

$html='<div class="item-price offer-price price-tc default-price">
$129.990
<span class="discount-2">-35%</span>
</div>
';
echo  (new DOMXPath(@DOMDocument::loadHTML($html)))->query("//div[contains(@class,'item-price')]/text()")->item(0)->textContent;

奖励:DOMDocument 和 DOMXPath 都是 php 内置的,使用 em 不需要外部库

【讨论】:

    猜你喜欢
    • 2014-08-13
    • 1970-01-01
    • 2015-03-14
    • 2015-11-05
    • 1970-01-01
    • 2013-12-25
    • 2013-12-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多