How to Get Open Graph Protocol of a Webpage by PHP

How to get Open Graph Protocol of a webpage by php?

When parsing data from HTML, you really shouldn't use regex. Take a look at the DOMXPath Query function.

Now, the actual code could be :

[EDIT] A better query for XPath was given by Stefan Gehrig, so the code can be shortened to :

libxml_use_internal_errors(true); // Yeah if you are so worried about using @ with warnings
$doc = new DomDocument();
$doc->loadHTML($html);
$xpath = new DOMXPath($doc);
$query = '//*/meta[starts-with(@property, \'og:\')]';
$metas = $xpath->query($query);
$rmetas = array();
foreach ($metas as $meta) {
$property = $meta->getAttribute('property');
$content = $meta->getAttribute('content');
$rmetas[$property] = $content;
}
var_dump($rmetas);

Instead of :

$doc = new DomDocument();
@$doc->loadHTML($html);
$xpath = new DOMXPath($doc);
$query = '//*/meta';
$metas = $xpath->query($query);
$rmetas = array();
foreach ($metas as $meta) {
$property = $meta->getAttribute('property');
$content = $meta->getAttribute('content');
if(!empty($property) && preg_match('#^og:#', $property)) {
$rmetas[$property] = $content;
}
}
var_dump($rmetas);

Is there a 'proper' way to extract Open Graph meta data in PHP?

I think your best option is fusonic/opengraph. Since it uses guzzle, and some symphony components. Although, as with most under-used PHP projects, check out a fork for updated dependencies, such as benallfree/opengraph.

You can add it via composer using require with a git url:

{
"require": {
"fusonic/opengraph": "dev-master"
},
"repositories": [
{
"type": "vcs",
"url": "https://github.com/benallfree/opengraph.git"
}
]
}

Open Graph protocol not working for my php website

Just changed http to https. Now it is working fine. (Followed the comment from Sky)



Related Topics



Leave a reply



Submit