DomDocument查询 [英] DomDocument Query

查看:85
本文介绍了DomDocument查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我对DomDocument领域非常陌生,我仍然在学习和寻找DomDocument中使用的xpath查询。html有时会更改,因此preg_match不是一个好主意。我需要从html文件中获取值。这是我想要获取的html部分。

Hi I am very new to this World of DomDocument,Im still learning and looking for xpath query use in DomDocument.The html sometimes changes so a preg_match is not a good idea. .I need to get the values from a html file.This is the part of html i want to get. I would be happy if you could help me..

 <?php  
    $doc = new DOMDocument();
    @$doc->loadHTML('<table cellspacing="0" cellpadding="0" align="center" class="results">
    <tr class="header" bgcolor="#0000FF">
    <td>
    </td>
    <td>Name/AKAs</td>
    <td>Age</td>
    <td>Location</td>
    <td>Possible Relatives</td>
    </tr>
    <tr>
    <td>1.</td>
        <td>
            <a class="LN" href=""><b>Iron, Man E</b></a>
        </td>
        <td align="center">54</td>
        <td>
            <a href="">Canada, AK</a><br />
            <a href="">California, AK</a><br />
        </td>
        <td>

        </td>
        <td>
            <a href="">View Details</a>
        </td>
    </tr>

    <tr><td>2.</td>
    <td>
    <a class="LN" href=""><b>Bat, Man E</b></a></td>
    <td align="center">26</td>
    <td>
    <a href="">Gotham, IA</a>
    <br /></td>
    <td>
    <a href=""> View Details</a></td></tr>
    </table>');
    $xpath = new DOMXPath($doc);
    $xquery = '//a[@class="LN"]';           
    $links = $xpath->query($xquery);   

    foreach ($links as $el) {
    echo strip_tags($doc->saveHTML($el)).'<br/>'; 
}

?>

我如何获得以下值?我只能得到 Iron,Man E Bat,Man E

How do i get the following value? I can only get Iron, Man E, and Bat, Man E

Iron, Man E | 54 | Canada, AK;California, AK
Bat, Man E | 26 | Gotham, IA


推荐答案

尝试一下,

$xquery = '//a'; // you will get all anchor tags now
$links = $xpath->query($xquery);   

foreach ($links as $el) {
   echo strip_tags($doc->saveHTML($el)).'<br/>'; 
}

尝试此操作以获取单行

$xpath = new DOMXPath($doc);
$xquery = '//tr[td[a]]';           
$links = $xpath->query($xquery);   
foreach ($links as $el) {
    echo strip_tags($doc->saveHTML($el)).'<br/>'; 
}

这篇关于DomDocument查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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