Search code examples
phphtmldomgetelementsbytagname

Using DOM (getElementsByTagName) to get "content" meta tag


Is it possible to get meta tags content using DOM (getElementsByTagName) for example

This the meta tag that i'm tring to get the content from.

<span class="nobr">
    <a href="/title/tt1981115/releaseinfo?ref_=tt_ov_inf " title="See all release dates"> 
        8 November 2013
        <meta itemprop="datePublished" content="2013-11-08">
        (USA)
    </a>            
</span>

And this is how i'm tring to get the meta content.

$metas = $dom->getElementsByTagName('meta');
for($i=0; $i <$metas-> length; $i++){
    $itemprop = $metas->item($i)->getAttribute("itemprop");
    if ($itemprop == "datePublished"){
        if ($metas->item($i)->textContent!=''){
            $res['published'] = $metas->item($i)->textContent;
        }
    }
}

Can someone tell me why won't it get the content?


Solution

  • Maybe you need value of content attribute?

    $metas = $dom->getElementsByTagName('meta');
    for($i=0; $i <$metas-> length; $i++){
        $itemprop = $metas->item($i)->getAttribute("itemprop");
        $content = $metas->item($i)->getAttribute("content");
        if ($itemprop == "datePublished" && $content !== ''){
            $res['published'] = $content;
        }
    }
    
    var_dump($res);
    

    Be careful, this code valid for the html example that shows in question. Just you can see direction of your code