首页 > 解决方案 > 如何在 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 );
    }
    ?>

标签: php

解决方案


getElementById将返回类型为的单个节点DOMNode。但是将始终返回一个不是 实例getElementsByTagName的数组,因此您的条件将失败。DOMNodesDOMNodeif

您可以尝试获取结果的第一个元素,该元素的类型为DOMNode.


推荐阅读