dongle19863 2012-07-04 04:56
浏览 33
已采纳

从html中提取信息?

First of all, I've seen a good deal of similar questions. I know regex or dom can be used, but I can't find any good examples of DOM and regex makes me pull my hair. In addition, I need to pull out multiple values from the html source, some simply contents, some attributes.

Here is an example of the html I need to get info from:

<div class="log">
    <div class="message">
        <abbr class="dt" title="time string">
            DATA_1
        </abbr>
        :
        <cite class="user">
            <a class="tel" href="tel:+xxxx">
                <abbr class="fn" title="DATA_2">
                    Me
                </abbr>
            </a>
        </cite>
        :
        <q>
            DATA_3
        </q>
    </div>
</div>

The "message" block may occur once or hundreds of times. I am trying to end up with data like this:

array(4) {
    [0] => array(3) {
               ["time"] => "DATA_1"
               ["name"] => "DATA_2"
               ["message"] => "DATA_3"
           }
    [1] => array(3) {
               ["time"] => "DATA_1"
               ["name"] => "DATA_2"
               ["message"] => "DATA_3"
           }
    [2] => array(3) {
               ["time"] => "DATA_1"
               ["name"] => "DATA_2"
               ["message"] => "DATA_3"
           }
    [3] => array(3) {
               ["time"] => "DATA_1"
               ["name"] => "DATA_2"
               ["message"] => "DATA_3"
           }
}

I tried using simplexml but it only seems to work on very simple html pages. Could someone link me to some examples? I get really confused since I need to get DATA_2 from a title attribute. What do you think is the best way to extract his data? It seems very similar to XML extraction which I have done, but I need to use some other method.

  • 写回答

2条回答 默认 最新

  • drex88669 2012-07-04 05:28
    关注

    Here is an example using DOMDocument and DOMXpath to parse your HTML.

    $doc = new DOMDocument;
    $doc->loadHTMLFile('your_file.html');
    $xpath = new DOMXpath($doc);
    
    $res = array();
    
    foreach ($xpath->query('//div[@class="message"]') as $elem) {
        $res[] = array(
            'time' => $xpath->query('abbr[@class="dt"]', $elem)->item(0)->nodeValue,
            'name' => $xpath->query('cite/a/abbr[@class="fn"]', $elem)->item(0)->getAttribute('title'),
            'message' => $xpath->query('q', $elem)->item(0)->nodeValue,
        );
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)