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
How to Properly Handle Session and Access Token with Facebook PHP Sdk 3.0
Which Coding Style You Use for Ternary Operator
How to Implement Ocr on a Website Using PHP
Laravel Eloquent - Attach VS Sync
Session Timeouts in PHP: Best Practices
Xampp: Couldn't Start Apache (Windows 10)
Php: $_Get and $_Post in Functions
How to Access Service Container in Symfony2 Global Helper Function (Service)
When to Use Index.PHP Instead of Index.Html
PHP - Csrf - How to Make It Works in All Tabs
How to Add 24 Hours to a Unix Timestamp in PHP
How to Run a .Sh File from PHP
How to Execute a Stored Procedure in PHP Using SQLsrv and "" Style Parameters
Why Is Calling a Function (Such as Strlen, Count etc) on a Referenced Value So Slow
Differencebetween PHP Require and Include