Jason Petkov
Jason Petkov

Reputation: 13

Get the content attribute value from a <meta> tag with a specified itemprop attribute value from an HTML string

I have an array which contains the following as one of its values:

<meta itemprop="datePublished" content="Mon Mar 04 08:52:45 PST 2013"/>

How do I extract the March 4th 2013 out of there? This is a dynamic field and will always be changing. I can't seem to find the right way to do it.

I want to be able to just echo $datepub; and just have the date.

Upvotes: 0

Views: 70

Answers (2)

Alvaro
Alvaro

Reputation: 41605

A very simple way could be exploding it:

//dividing the string by whitespaces
$parts = explode(' ', $datepub);  

echo $parts[1]; //month (Mar)
echo $parts[2]; //day (04)
echo $parts[5]; //year (2013)

Then you could make use of createFromFormat function to convert it to any other desirable format:

//creating a valid date format
$newDate = DateTime::createFromFormat('d/M/Y', $parts[1].'/'.$parts[2].'/'.$parts[5]);

//formating the date as we want
$finalDate = $newDate->format('F jS Y'); //March 4th 2013

Upvotes: 1

Chris L
Chris L

Reputation: 616

To expand on Marc B's answer with a code example using SimpleXML:

$data = '<?xml version="1.0"?><meta itemprop="datePublished" content="Mon Mar 04 08:52:45 PST 2013"/>'; // your XML
$xml = simplexml_load_string($data);

// select all <meta> nodes in the document that have the "content" attribute
$xpath1 = $xml->xpath('//meta[@content]');
foreach ($xpath1 as $key => $node) {
    echo $node->attributes()->content; // Mon Mar 04 08:52:45 PST 2013
}

// Marc B's select "content" attribute for all <meta> nodes in the document
$xpath2 = $xml->xpath('//meta/@content');
foreach ($xpath2 as $key => $node) {
    echo $node->content; // Mon Mar 04 08:52:45 PST 2013
}

Upvotes: 0

Related Questions