[英]PHP XPath - breaking HTML content into nodes (include empty nodes)
我正在嘗試將 HTML 字符串分解為帶有文本內容的單個節點(如果為空則不分解)。
這是我擁有的 HTML 字符串:
<p>Paragraph one.</p>
<p><strong>Paragraph <em>two</em></strong>.</p>
<p>Some <strong>other paragraph</strong> three.</p>
<p>Last paragraph - paragraph four.</p>
<table>
<tbody>
<tr>
<td>Table paragraph one</td>
<td>Table paragraph two</td>
</tr>
<tr>
<td></td>
<td>Table paragraph four</td>
</tr>
</tbody>
</table>
我目前擁有的代碼幾乎達到了我想要的效果:
$document = new DOMDocument();
$document->loadXML('<div class="root">'.$content.'</div>');
$xpath = new DOMXpath($document);
$nodes = $xpath->evaluate('//text()');
foreach($nodes as $node) {
echo $node->getNodePath();
echo '<br>';
echo $node->textContent;
echo '<hr>';
}
但它不會包括空節點,比如這個表格單元格(下面的結果 - tr[2]/td[1] 不在列表中)。 如何強制它包含沒有任何#text 的空節點,並且不創建重復項?
當前結果:
/div/p[1]/text()
Paragraph one.
/div/p[2]/strong/text()
Paragraph
/div/p[2]/strong/em/text()
two
/div/p[2]/text()
.
/div/p[3]/text()[1]
Some
/div/p[3]/strong/text()
other paragraph
/div/p[3]/text()[2]
three.
/div/p[4]/text()
Last paragraph - paragraph four.
/div/table/tbody/tr[1]/td[1]/text()
Table paragraph one
/div/table/tbody/tr[1]/td[2]/text()
Table paragraph two
/div/table/tbody/tr[2]/td[2]/text()
Table paragraph four
如您所見,不包括空節點。 我如何包括它們? 謝謝。
這個版本的$nodes
應該讓你足夠接近,但不完全是你預期的 output:
$nodes =$xpath->evaluate("//text() | //*[not(text())]");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.