php - 如何在 PHP 中使用 getElementsByTagName 获取 innerHTML
问题描述
下面是我的 PHP 代码。我可以innerHTML
使用$node = $doc->getElementById( 'first' );
,但我在使用时无法innerHTML
使用$doc->getElementsByTagName('td');
这<td>
是我的代码:$html2 = '<td width="112"><p><span lang="EN-US">Question </span></p></td>';
<?php
//$html = '<div id="first"><h1>Hello</h1></div><div id="second"><p>World!</p></div>';
$html2 = '<td width="112"><p><span lang="EN-US">Question </span></p></td>';
$doc = new \DOMDocument();
$doc->loadHTML( $html2 );
//$node = $doc->getElementById( 'first' );
$node = $doc->getElementsByTagName('td');
if( $node instanceof \DOMNode ) {
echo innerHTML( $node, true );
//Output: <div id="first"><h1>Hello</h1></div>
echo innerHTML( $node, false );
// Output: <h1>Hello</h1>
}
function innerHTML( \DOMNode $node, $include_target_tag = true ) {
$doc = new \DOMDocument();
$doc->appendChild( $doc->importNode( $node, true ) );
$html = trim( $doc->saveHTML() );
if ( $include_target_tag ) {
return $html;
}
return preg_replace( '@^<' . $node->nodeName . '[^>]*>|</' . $node->nodeName . '>$@', '', $html );
}
?>
解决方案
getElementById
将返回类型为的单个节点DOMNode
。但是将始终返回一个不是 实例getElementsByTagName
的数组,因此您的条件将失败。DOMNodes
DOMNode
if
您可以尝试获取结果的第一个元素,该元素的类型为DOMNode
.
推荐阅读
- django-rest-framework - DRF Social OAuth2 中的某些设置似乎无用
- node.js - 如何解决节点js请求中的1020错误
- google-apps-script - 如何在 doGet 函数中调用函数?
- c - C 编程中的奇怪行为
- python - versionalchemy.exceptions.LogTableCreationError:需要注册 va 表
- php - 我在 laravel 中得到字符串而不是数组
- android - 找不到 AndroidJUnit4 的委托运行程序 androidx.test.internal.runner.junit4.AndroidJUnit4ClassRunner
- c++ - 这个错误是什么意思,我该如何解决:错误LNK2005:“
" 已经定义在 - r - 使用 R 与 Chi、Cramér 和 Fisher 进行多列联表分析
- python - Ray:多处理差异(类与函数)