[英]PHP DOMDocument table but leave inner HTML content
I'm trying to display each row in a HTML table and leave the inner HTML tags in the results but I can't get it to work and it keeps stripping the HTML inner tags what is the best for me to get each row from a HTML table and leave the inner HTML tags in the results? 我正在尝试在HTML表格中显示每一行,并在结果中保留内部HTML标记,但我无法使其工作,并且它不断剥离HTML内部标记对我来说最好从每个行获取一行HTML表格并在结果中保留内部HTML标记?
This is the code I'm currently working with to get this working: 这是我正在使用的代码,以使其工作:
<?php
function tdrows($elements){
$str = "";
foreach ($elements as $element) {
$str .= $element->nodeValue . ", ";
}
return $str;
}
function getdata(){
$content = "<table border="0" cellspacing="0" cellpadding="0" class="ta1"><colgroup><col width="99"/><col width="99"/><col width="99"/><col width="99"/></colgroup><tr class="ro1"><td style="text-align:left;width:2.267cm; " class="ce1"><p>Col A</p></td><td style="text-align:left;width:2.267cm; " class="ce2"><p>Col B</p></td><td style="text-align:left;width:2.267cm; " class="ce3"><p>Col C</p></td><td style="text-align:left;width:2.267cm; " class="ce5"><p>Col D</p></td></tr><tr class="ro2"><td style="text-align:left;width:2.267cm; " class="Default"><p>This <span class="T1">is</span> a test</p></td><td style="text-align:left;width:2.267cm; " class="Default"><p>This is a <span class="T2">test</span></p></td><td style="text-align:left;width:2.267cm; " class="ce4"><p>This<span class="T3"> is</span> a test<span class="T4">2</span></p></td><td style="text-align:left;width:2.267cm; " class="Default"><p>This is a test</p></td></tr></table>";
$DOM = new DOMDocument;
$DOM->loadHTML($contents);
$items = $DOM->getElementsByTagName('tr');
foreach ($items as $node) {
echo tdrows($node->childNodes) . "<br />";
}
}
getdata();
It's currently display in the following what is correct but it's missing the inner HTML tags. 它目前显示在下面是正确的,但它缺少内部HTML标记。
Col A, Col B, Col C, Col D,
This is a test, This is a test, This is a test2, This is a test,
Maybe I'm looking at it wrong and there should be another way for me to extract the information from a table to get the correct result. 也许我看错了,我应该有另一种方法从表中提取信息以获得正确的结果。 Any help would be grateful. 任何帮助将不胜感激。
DOMNode->nodeValue
is equivalent to DOMNode->textContent
for DOMElement
(which is a derivative of DOMNode
); DOMNode->nodeValue
等同于DOMElement
DOMNode->textContent
(它是DOMNode
的衍生物); it will only give you the text content of itself and all its descendant nodes. 它只会给你自己及其所有后代节点的文本内容。
If you want the HTML as well, you should use DOMDocument::saveHTML( DOMNode $node = null )
, with something like this: 如果你也想要HTML,你应该使用DOMDocument::saveHTML( DOMNode $node = null )
,如下所示:
function tdrows($elements){
$str = "";
foreach ($elements as $element) {
$str .= $element->ownerDocument->saveHTML( $element );
}
return $str;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.