【问题标题】:Extract DOM-elements from string, in PHP [duplicate]在PHP中从字符串中提取DOM元素[重复]
【发布时间】:2011-07-04 20:39:00
【问题描述】:

可能的重复:
crawling a html page using php?
Best methods to parse HTML

我的 php 脚本中有一个字符串变量,它包含 html 页面。我如何从这个字符串中提取 DOM 元素?

例如,在这个字符串'<div class="someclass">text</div>' 中,我希望得到变量'text'。我该怎么做?

【问题讨论】:

标签: php html string domdocument


【解决方案1】:

您需要使用DOMDocument 类,更具体地说,它的loadHTML 方法,将您的HTML 字符串加载到DOM 对象。

例如:

$string = <<<HTML
<p>test</p>
<div class="someclass">text</div>
<p>another</p>
HTML;

$dom = new DOMDocument();
$dom->loadHTML($string);


之后,您将能够操作 DOM,例如使用 DOMXPath 类对其进行 XPath 查询。

例如,在您的情况下,您可以使用基于这部分代码的内容:

$xpath = new DOMXpath($dom);
$result = $xpath->query('//div[@class="someclass"]');
if ($result->length > 0) {
    var_dump($result->item(0)->nodeValue);
}

这里会得到以下输出:

string 'text' (length=4)


作为替代方案,您也可以使用simplexml_load_stringSimpleXMLElement::xpath 而不是DOMDocument——但对于复杂的操作,我通常更喜欢使用DOMDocument

【讨论】:

  • @Gordon done (是的,这有点像多次重复)
  • DOMDocument 有多快?
【解决方案2】:

看看DOMDocumentDOMXPath

$DOM = new DOMDocument();
$DOM->loadHTML($str);

$xpath = new DOMXPath($DOM);
$someclass_elements = $xpath->query('//[@class = "someclass"]');
// ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-09
    • 2019-03-04
    • 2016-10-20
    • 1970-01-01
    • 1970-01-01
    • 2014-04-08
    • 2013-12-10
    相关资源
    最近更新 更多