如何在php dom中获取标签的名称?

时间:2014-07-30 13:10:49

标签: php html dom

我编写了一个代码来获取内容。但是这些内容可能是照片或视频。我可以获得标签的名称吗?我的代码:

$content = strip_tags($content, '<img><iframe>');

如果内容是照片,则输出为:

$content = <img src="http://exxample.com" class="img-responsive">

如果内容是视频,则输出为:

$content = <iframe src="http://exxample.com"></iframe>

我想得到:

img或iframe

我尝试使用getElementByTagName,但需要父标记来获取子节点。

编辑:我用它来获取所有内容:

$content = Utilities::getContentBetween($html, "itemBody");

static function getContentBetween($html, $class)
{
    $doc = new DOMDocument();
    libxml_use_internal_errors(true);
    $doc->loadHTML($html);
    $finder = new DomXPath($doc);
    $node = $finder->query("//div[@class='".$class."']");
    return $doc->saveHTML($node->item(0));
}

然后我用它来获取img或iframe标签:

$content = strip_tags($content, '<img><iframe>');

EDIT2: 如果内容是视频:

<div class="itemBody">
    <div class="clr"></div>
                    <meta property="og:image" content="http://img.youtube.com/vi/EfA0slJamjI/hqdefault.jpg"/>
        <span class="itemVideo">
    <div class="avPlayerWrapper avVideo">
        <div style="width:560px;" class="avPlayerContainer">
            <div id="AVPlayerID_7a182346_2039535915" class="avPlayerBlock">
                <iframe src="http://www.youtube.com/embed/EfA0slJamjI?rel=0&amp;fs=1&amp;wmode=transparent" width="560" height="315" frameborder="0" allowfullscreen title="JoomlaWorks AllVideos Player"></iframe>                 </div>
        </div>
    </div>
 </span>
    <div class="clr"></div>
</div>

如果内容是图片:

<div class="itemBody">
<div class="catItemImageBlock">
    <span class="catItemImage"> <a
        href="/item/29780-how-to-cook.html"
        title="How to cook?">
            <img src="/media/k2/items/cache/100f4197fe779a7a85aba6772f82c790_L.jpg"
            alt="how to cook?"
            class="img-responsive" /> </a> </span>
    <div class="clr"></div>
</div>
<div class="clr"></div>
<div class="clr"></div>
</div>

1 个答案:

答案 0 :(得分:0)

$img = $finder->getElementsByTagName('img');

$iframe= $finder->getElementsByTagName('iframe');

它可以获得特定标签。如果你需要获取内部内容,请使用getAttribute()

LIKE $iframe->getAttribute('src');