Doug Fir
Doug Fir

Reputation: 21204

Grabbing inner html using php

I'm creating meta tags for search and open graph.

For the meta description tag I'd like to set the value dynamically based upon the concatenation of the content of two html elements on the page.

For example if this is a snippet of my html:

<div class="report-description-text">
            <h5>Description</h5>
            Set of drawers          
<br/>

And another snippet elsewhere on the document is:

<p class="report-when-where">
            <span class="r_date">09:58 Apr 5 2014 </span>
            <span class="r_location">123 main St, Toronto, ON, Canada</span>
                    </p>

I would like my meta tag to be:

echo '    
<meta name="description" content="Set of drawers at 123 main St, Toronto, ON, Canada" />

Little new to php and code in general. I did some research on this site too and found an answer along the lines of using DOMinnerHTML and a foreach function.

Is that the simplest way? How would I do this?

Upvotes: 0

Views: 121

Answers (1)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89547

A way using DOMDocument and XPath:

$dom = new DOMDocument();
@$dom->loadHTML($html);

$xpath = new DOMXPath($dom);

$query = '//div[@class = "report-description-text"]/h5[.="Description"]'
       . '/following-sibling::text()[1]';
$description = trim($xpath->query($query)->item(0)->textContent);

$query = '//p[@class = "report-when-where"]/span[@class = "r_location"]/text()';
$location = trim($xpath->query($query)->item(0)->textContent);

$meta = $dom->createElement('meta');
$meta->setAttribute('name', 'Description');
$meta->setAttribute('content', $description . ' at ' . $location);

// only needed if the head tag doesn't exist
if (!$dom->getElementsByTagName('head')->item(0)):
    $head = $dom->createElement('head');
    $dom->getElementsByTagName('html')->item(0)->insertBefore($head,
        $dom->getElementsByTagName('body')->item(0));
endif;

$dom->getElementsByTagName('head')->item(0)->appendChild($meta);

$result = $dom->saveHTML(); // or saveXML if you want xhtml

echo htmlspecialchars($result);

Upvotes: 2

Related Questions