【问题标题】:HTML DOM Document parsingHTML DOM 文档解析
【发布时间】:2012-12-04 04:44:49
【问题描述】:

我是 DOM 文档的新手.. 我有这个 html:

    <tr class="calendar_row" data-eventid="39657">
        <td class="alt1 eventDate smallfont" align="center">Sun<div class="eventday_multiple">Dec 9</div></td>
        <td class="alt1 smallfont" align="center">3:34am</td>
        <td class="alt1 smallfont" align="center">USD</td>
    </tr>

    <tr class="calendar_row" data-eventid="39658">
        <td class="alt1 eventDate smallfont" align="center">Sun<div class="eventday_multiple">Dec 10</div></td>
        <td class="alt1 smallfont" align="center">5:14am</td>
        <td class="alt1 smallfont" align="center">EUR</td>
    </tr>

我正在尝试使用此代码首先获取 tr 中的内容:

    $ret = array();
    libxml_use_internal_errors(true); 
    $doc = new DOMDocument();
    $doc->loadHTML($html);
    //$doc->saveHTMLFile('textbox.php');

    $text = $doc->getElementsByTagName('tr');
    foreach ($text as $tag){
        $ret[] = $doc->saveHtml($tag); 
        echo $doc->saveHtml($tag); 
    }

我不知道为什么要回显的值是整个文档而不是 tr 中的值..

其次,我还想获取 td 标签之间的值,例如 5:14 AM、EUR 等。但我不知道该怎么做。

请原谅菜鸟问题..

最好的问候

【问题讨论】:

    标签: php html dom domdocument


    【解决方案1】:
    $doc = new DOMDocument();
    $doc ->loadHTML("$html");
    $tables = $doc->getElementsByTagName('table');
    $table = $tables->item(0);//takes the first table in dom
    
    foreach ($table->childNodes as $td) {
      if ($td->nodeName == 'td') {
        echo $td->nodeValue, "\n";
      }
    }
    

    【讨论】:

    • 查看我的编辑,如果这也不起作用,那么您的 $html 可能是错误的。
    【解决方案2】:

    将元素传递给saveHtml 会生成元素outerHTML 而不是它的innerHTML,因此您可以获得它的标签属性和它的所有内容。当然你需要运行 PHP>=5.3.6 。

    td 之间的值可以通过$td-&gt;firstChild-&gt;nodeValue; 或只是$td-&gt;textContent; 获得,其中$td 是有问题的&lt;td&gt;

    【讨论】:

    • 对不起,我将如何使用 $td->textContent;.. 我不知道该放在哪里
    • @Vainglory07 你真的没有用它做你想做的事,所以我不能说你会如何使用它。如果您不知道如何获取&lt;td&gt;s,只需在 tr 上使用 getElementsByTagName 即可。
    猜你喜欢
    • 2010-11-28
    • 1970-01-01
    • 1970-01-01
    • 2012-11-02
    • 1970-01-01
    • 2013-08-15
    • 1970-01-01
    • 2016-05-27
    • 2013-02-06
    相关资源
    最近更新 更多