我是简单HTML DOM解析器的新手。我想从以下HTML中获取子元素:
<div class="article">
<div style="text-align:justify">
<img src="image.jpg" title="image">
<br>
<br>
"Text to grab"
<div>......</div>
<br></br>
................
................
</div>
</div>
我正在尝试将文字“Text to grab”
到目前为止,我已尝试过以下查询:
$html->find('div[class=article] div')->children(3);
但它不起作用。知道如何解决这个问题吗?
答案 0 :(得分:3)
你在这里不需要simple_html_dom
。可以使用DOMDocument
和DOMXPath
来完成。两者都是PHP核心的一部分。
示例:
// your sample data
$html = <<<EOF
<div class="article">
<div style="text-align:justify">
<img src="image.jpg" title="image">
<br>
<br>
"Text to grab"
<div>......</div>
<br></br>
................
................
</div>
</div>
EOF;
// create a document from the above snippet
// if you are loading from a remote url use:
// $doc->load($url);
$doc = new DOMDocument();
$doc->loadHTML($html);
// initialize a XPath selector
$selector = new DOMXPath($doc);
// get the text node (also text elements in xml/html are nodes
$query = '//div[@class="article"]/div/br[2]/following-sibling::text()[1]';
$textToGrab = $selector->query($query)->item(0);
// remove newlines on start and end using trim() and output the text
echo trim($textToGrab->nodeValue);
输出:
"Text to grab"
答案 1 :(得分:1)
如果它总是在同一个地方你可以做到:
$html->find('.article text', 4);