我应该如何在php中使用dom获得像这样的div内容? [英] How should I get a div's content like this using dom in php?

查看:68
本文介绍了我应该如何在php中使用dom获得像这样的div内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

div就是这样

<div style="width:90%;margin:0 auto;color:#Black;" id="content">
this is text, severaltags
</div> 

我应该如何在php中使用dom获取div的内容,包括
标记?

how should i get the div's content including the
tags using dom in php?

推荐答案

假设您使用的是PHP5,则可以使用 DOMDocument -注意这没有提供检索元素内部html的简单方法。您可以执行以下操作:

Assuming your using PHP5 you can use DOMDocument -- take note that this doesn't provide simple means for retrieving inner html of an element. You can do something along the following:

function DOMinnerHTML($element) 
{ 
    $innerHTML = ""; 
    $children = $element->childNodes; 
    foreach ($children as $child) 
    { 
        $tmp_dom = new DOMDocument(); 
        $tmp_dom->appendChild($tmp_dom->importNode($child, true)); 
        $innerHTML.=trim($tmp_dom->saveHTML()); 
    } 
    return $innerHTML; 
} 

$dom = new DOMDocument();

$dom->loadHTML($html);

$items = $dom->getElementsByTagName('div');
if ($items->length)
{
    $innerHTML = DOMinnerHTML($items->item(0));
}

echo $innerHTML;

对于这种简单的东西,尽管我通常不建议这样做,但我会使用正则表达式:

For something this simple, although I don't normally recommend it, I'd use regex:

preg_match('|<div[^>]+>(.*?)</div>|is', $html, $match);

if ($match)
{
    echo 'html is: ' . $match[1][0];
}

这篇关于我应该如何在php中使用dom获得像这样的div内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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