如何使用DomDocument获取子元素? [英] How to use DomDocument to get child elements?

查看:119
本文介绍了如何使用DomDocument获取子元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用php dom获取子元素的文本。
具体来说,我想在每个< tr> < a> 标记>。

I am trying to get the text of child elements using the php dom. Specifically, I am trying to get only the first <a> tag within every <tr>.

HTML就像这样......

The HTML is like this...

<table>
<tbody>
    <tr>
        <td>
            <a href="#">1st Link</a>
        </td>
        <td>
            <a href="">2nd Link</a>
        </td>
        <td>
            <a href="#">3rd Link</a>
        </td>
    </tr>

    <tr>
        <td>
            <a href="#">1st Link</a>
        </td>
        <td>
            <a href="#">2nd Link</a>
        </td>
        <td>
            <a href="#">3rd Link</a>
        </td>
    </tr>
</tbody>
</table>

我对它的悲惨尝试涉及使用 foreach()循环,但只会在 print_r()时返回 Array() > $ aVal 。

My sad attempt at it involved using foreach() loops, but would only return Array() when doing a print_r() on the $aVal.

$dom = new DOMDocument();
libxml_use_internal_errors(true);       
$dom->loadHTML(returnURLData($url));
libxml_use_internal_errors(false);

$tables = $dom->getElementsByTagName('table');
$aVal = array();

foreach ($tables as $table) {
    foreach ($table as $tr){
        $trVal = $tr->getElementsByTagName('tr');
        foreach ($trVal as $td){
            $tdVal = $td->getElementsByTagName('td');
            foreach($tdVal as $a){
                $aVal[] = $a->getElementsByTagName('a')->nodeValue;
            }
        }
    }
}

Am我在正确的轨道上还是完全关闭?

Am I on the right track or am I completely off?

推荐答案

将此代码放入test.php

Put this code in test.php

require 'simple_html_dom.php';
$html = file_get_html('test1.php');
foreach($html->find('table tr') as $element)
{
    foreach($element->find('a',0) as $element)
    {
        echo $element->plaintext;
    }
}

并将你的html代码放在test1.php中

and put your html code in test1.php

<table>
    <tbody>
        <tr>
            <td>
                <a href="#">1st Link</a>
            </td>
            <td>
                <a href="">2nd Link</a>
            </td>
            <td>
                <a href="#">3rd Link</a>
            </td>
        </tr>

        <tr>
            <td>
                <a href="#">1st Link</a>
            </td>
            <td>
                <a href="#">2nd Link</a>
            </td>
            <td>
                <a href="#">3rd Link</a>
            </td>
        </tr>
    </tbody>
</table>

这篇关于如何使用DomDocument获取子元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆