A Laravel package to fetch Open Graph data of a website.

Overview

Laravel OpenGraph

OpenGraph is a laravel package to fetch Open Graph metadata of a website/link.

Latest Version on Packagist Total Downloads Scrutinizer Code Quality StyleCI CodeFactor Build Status FOSSA Status

Features

  • Easily fetch metadata of a URL. Laravel OpenGraph fetches all the metadata of a URL.

  • Supports language-specific metadata. Laravel OpenGraph can fetch metadata in a specific language if webpage supports.

  • Supports twitter metadata. Laravel OpenGraph supports twitter OG data too.

  • Verify image URL. Laravel OpenGraph verifies that the image URL in the image metadata is valid or not.

Demo

  curl https://laravelopengraph.herokuapp.com/api/fetch?url=ogp.me&allMeta=true&language=en_GB

How to use Laravel OpenGraph

An article can be found on the medium blog: https://hackernoon.com/how-to-fetch-open-graph-metadata-in-laravel-2d5d674904d7

Documentation

https://opengraph.shashi.dev

Installation

Perform the following operations in order to use this package

  • Install via composer
composer require "shweshi/opengraph"

If you do not run Laravel 5.5 (or higher), then add the service provider in config/app.php:

  • Add Service Provider Open config/app.php and add shweshi\OpenGraph\Providers\OpenGraphProvider::class, to the end of providers array:

    'providers' => array(
        ....
        shweshi\OpenGraph\Providers\OpenGraphProvider::class,
    ),
    

    Next under the aliases array:

    'aliases' => array(
        ....
        'OpenGraph' => shweshi\OpenGraph\Facades\OpenGraphFacade::class
    ),
    

If you do run the package on Laravel 5.5+, package auto-discovery takes care of the magic of adding the service provider.

Requirements

  • You need to install the DOM extension.

How to use

  • After following the above steps,

    use OpenGraph;
    
    $data = OpenGraph::fetch("https://unsplash.com/");
    

    this will give you an array like this...

      array (
        'title' => 'Beautiful Free Images & Pictures | Unsplash',
        'description' => 'Beautiful, free images and photos that you can download and use for any project. Better than any royalty free or stock photos.',
        'type' => 'website',
        'url' => 'https://unsplash.com/',
        'image' => 'http://images.unsplash.com/photo-1542841791-1925b02a2bbb?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=1080&fit=max&ixid=eyJhcHBfaWQiOjEyMDd9&s=aceabe8a2fd1a273da24e68c21768de0',
        'image:secure_url' => 'https://images.unsplash.com/photo-1542841791-1925b02a2bbb?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=1080&fit=max&ixid=eyJhcHBfaWQiOjEyMDd9&s=aceabe8a2fd1a273da24e68c21768de0',
      )
    

    You can also pass an optional parameter either true or false along with URL. When set false it will only fetch basic metadata and in case of true it will fetch all the other optional metadata as well like audio, video, music and twitter metatags as well.

    $data = OpenGraph::fetch("https://unsplash.com/", true);
    

    this will give you an array like this...

      array (
        'charset' => 'UTF8',
        'viewport' => 'width=device-width, initial-scale=1.0, maximum-scale=1.0, minimal-ui',
        'mobile-web-app-capable' => 'yes',
        'apple-mobile-web-app-capable' => 'yes',
        'apple-mobile-web-app-title' => 'Unsplash',
        'application-name' => 'Unsplash',
        'author' => 'Unsplash',
        'msapplication-config' => 'browserconfig.xml',
        'msapplication-TileColor' => '#ffffff',
        'msapplication-TileImage' => 'https://unsplash.com/mstile-144x144.png',
        'theme-color' => '#ffffff',
        'description' => 'Beautiful, free images and photos that you can download and use for any project. Better than any royalty free or stock photos.',
        'twitter:site' => '@unsplash',
        'twitter:title' => 'Beautiful Free Images & Pictures | Unsplash',
        'twitter:description' => 'Beautiful, free images and photos that you can download and use for any project. Better than any royalty free or stock photos.',
        'twitter:url' => 'https://unsplash.com/',
        'twitter:card' => 'summary_large_image',
        'twitter:image' => 'https://images.unsplash.com/photo-1546486610-e9fe4f1e6751?ixlib=rb-1.2.1&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=1080&fit=max&ixid=eyJhcHBfaWQiOjEyMDd9',
        'title' => 'Beautiful Free Images & Pictures | Unsplash',
        'type' => 'website',
        'url' => 'https://unsplash.com/',
        'image' => 'http://images.unsplash.com/photo-1546486610-e9fe4f1e6751?ixlib=rb-1.2.1&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=1080&fit=max&ixid=eyJhcHBfaWQiOjEyMDd9',
        'image:secure_url' => 'https://images.unsplash.com/photo-1546486610-e9fe4f1e6751?ixlib=rb-1.2.1&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=1080&fit=max&ixid=eyJhcHBfaWQiOjEyMDd9',
    )
    

    To fetch the metadata in a specific language you can pass the language as the third argument, this value will be used as the Accept-Language header.

    $url = "https://ogp.me",
    $allMeta = true, // can be false
    $language = 'en' // en-US,en;q=0.8,en-GB;q=0.6,es;q=0.4
    $data = OpenGraph::fetch($url, $allMeta, $language);
    

    You can also pass additional Libxml parameters as the fourth argument ($options) https://www.php.net/manual/en/libxml.constants.php. Default options are set to suppress the reporting of errors and warnings

    $data = OpenGraph::fetch($url, $allMeta, $language, $options);  
    

    You can use the fifth parameter to set the user-agent ($userAgent) of the request. The default is 'Curl'.

    $data = OpenGraph::fetch($url, $allMeta, $language, $options, $userAgent);  
    

Exception Handling

The fetch() method, returns a FetchException with aditional data at failure.

    try {
        $data = OpenGraph::fetch($url, true);
    } catch (shweshi\OpenGraph\Exceptions\FetchException $e) {
        $message = $e->getMessage();
        $data = $e->getData();
    }

Testing

composer test

Changelog

Please see CHANGELOG for more information what has changed recently.

Contributing

Please see CONTRIBUTING and CODE OF CONDUCT for details.

License

The MIT License (MIT). Please see License File for more information.

FOSSA Status

Happy coding!

Comments
  • Unable to retrieve og data for FB posts

    Unable to retrieve og data for FB posts

    Hi Team, Before I speak about the issue, I would first like to say that the package does a very good job on almost all urls. Great job !

    To speak about the issue I am facing, am having troubles only with retrieving og data for FB posts url. The result appears empty. However this is not the case when I use this package with twiiter urls, blogs, instagram urls. So I am here to seek some help in case am missing something in the way am accessing it.

    TIA

    closed 
    opened by Yashaswini 7
  • Bug Fix: SSL get headers image verification

    Bug Fix: SSL get headers image verification

    Fixes a bug related to Issue #83 on main repository where after verifying the problem it was determined that SSL marked as Wildcard ( * ) can cause problems with "get_headers" function in php.

    It was assumed previously that "FILTER_VALIDATE_URL" was being too strict, but later determined that SSL verification was failing.

    opened by ItsSkynet 6
  • Twitter post images not generating inside image tag due to verify_image_url function

    Twitter post images not generating inside image tag due to verify_image_url function

    Describe the bug verify_image_url Function is assuming twitter post images with ":orig", ":large" ":medium" or ":small" as invalid images and thus is sending empty image value on the fetch return array.

    Generated example:

    Array
    (
        [0] => Array
            (
                [robots] => NOODP
                [msapplication-TileImage] => //abs.twimg.com/favicons/win8-tile-144.png
                [msapplication-TileColor] => #00aced
                [facebook-domain-verification] => moho2ug7zs57jijiywrewd8wb5a08h
                [swift-page-name] => permalink
                [swift-page-section] => permalink
                [al:ios:url] => twitter://status?id=1524828581536440320
                [al:ios:app_store_id] => 333903271
                [al:ios:app_name] => Twitter
                [al:android:url] => twitter://status?status_id=1524828581536440320
                [al:android:package] => com.twitter.android
                [al:android:app_name] => Twitter
                [type] => article
                [url] => https://twitter.com/MexicanSkynet/status/1524828581536440320
                [title] => SKYNΞT | 🔴 twitch.tv/mexicanskynet on Twitter
                [image] =>  
                [image:user_generated] => true
                [description] => “Hoy tenemos el mas pintoresco y tradicional torneo M7GP a las 9:00 pm CUU / 10:00 pm CDMX
    
    Recuerda unirte al chat de voz: https://t.co/GGyxQJteMB
    y recuerda sintonizarnos por: https://t.co/L0KmK5iRHt
    
    #MarioKart8Deluxe #mariokart #nintendoswitch #twitchaffiliate”
                [site_name] => Twitter
                [fb:app_id] => 2231777543
            )
    
    )
    

    After commenting line 56 trough line 51 in src/OpenGraph.php it successfully generated the image url on this example:

    Array
    (
        [0] => Array
            (
                [robots] => NOODP
                [msapplication-TileImage] => //abs.twimg.com/favicons/win8-tile-144.png
                [msapplication-TileColor] => #00aced
                [facebook-domain-verification] => moho2ug7zs57jijiywrewd8wb5a08h
                [swift-page-name] => permalink
                [swift-page-section] => permalink
                [al:ios:url] => twitter://status?id=1524828581536440320
                [al:ios:app_store_id] => 333903271
                [al:ios:app_name] => Twitter
                [al:android:url] => twitter://status?status_id=1524828581536440320
                [al:android:package] => com.twitter.android
                [al:android:app_name] => Twitter
                [type] => article
                [url] => https://twitter.com/MexicanSkynet/status/1524828581536440320
                [title] => SKYNΞT | 🔴 twitch.tv/mexicanskynet on Twitter
                [image] => https://pbs.twimg.com/media/FSlHM2bWIAAQn-8.jpg:large
                [image:user_generated] => true
                [description] => “Hoy tenemos el mas pintoresco y tradicional torneo M7GP a las 9:00 pm CUU / 10:00 pm CDMX
    
    Recuerda unirte al chat de voz: https://t.co/GGyxQJteMB
    y recuerda sintonizarnos por: https://t.co/L0KmK5iRHt
    
    #MarioKart8Deluxe #mariokart #nintendoswitch #twitchaffiliate”
                [site_name] => Twitter
                [fb:app_id] => 2231777543
            )
    
    )
    

    Expected behavior Url array key should be populated if a twitter post has an image.

    ** System ** Laravel 8 PHP 7.4

    Side note anyone having problems getting metadata from socialmedia please use the following user agent set on this example: $opg_array = OpenGraph::fetch('URL', true, null, null, 'facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)');

    enhancement help wanted good first issue 
    opened by ItsSkynet 3
  • Error when using

    Error when using

    Hello how are you? I started getting this error when using...

    [2022-03-18 21:45:05] local.ERROR: Using $this when not in object context {"exception":"[object] (Error(code: 0): Using $this when not in object context at [...]back-end\vendor\shweshi\opengraph\src\OpenGraph.php:12)

    Laravel 8.x My code: if (!$validator->fails()) { $data_group = OpenGraph::fetch($request->link); $validator->after(function ($validator) use ($data_group) { if(empty($data_group['title'])) { $validator->errors()->add('link', 'Error'); } }); } I don't understand its origin or how to solve it...

    opened by LeonardoSartor 3
  • Doesn't get the open graph data from Netflix

    Doesn't get the open graph data from Netflix

    It doesn't seem to parse the open graph data from Netflix correctly.

    When you fetch the open graph data from Netflix (any page on netflix.com) using OpenGraph::fetch('view-source:https://www.netflix.com/nl-en/title/70180387', true)

    it only returns:

    [
        "viewport" => "width=device-width, initial-scale=1",
    ]
    

    while the tags seem to be present in the source:

    <meta property="og:title" content="Homeland | Netflix"/>
    <meta property="og:description" content="CIA analyst Carrie Mathison struggles with mental health and family issues while leading the war against terrorism in this political thriller series."/>
    <meta property="og:url" content="https://www.netflix.com/nl-en/title/70180387" id="meta-url"/>
    <meta property="og:image" content="https://occ-0-435-769.1.nflxso.net/dnm/api/v6/E8vDc_W8CLv7-yMQu8KMEC7Rrr8/AAAABecpPMdDJbTCAHnkTPNz5_MTnRfgAQ8NuGi1h2O_FZ5y-IcWYq-PZWQ9GhQ0zreFSDbmz48qepCON5qbqtFDq_wJn7dJ.jpg?r=286"/>
    <meta property="al:ios:url" content="nflx://www.netflix.com/title/70180387?locale=en-NL"/>
    <meta property="al:ios:app_store_id" content="363590051"/>
    <meta property="al:ios:app_name" content="Netflix"/>
    <meta property="al:android:url" content="nflx://www.netflix.com/title/70180387?locale=en-NL"/>
    <meta property="al:android:package" content="com.netflix.mediaclient"/>
    <meta property="al:android:app_name" content="Netflix"/>
    <meta name="twitter:card" content="summary_large_image"/><meta name="twitter:site" content="@netflix"/>
    
    opened by sebastiaands 3
  • Log errors from DOMDocument::loadHTML() using libxml_get_errors()

    Log errors from DOMDocument::loadHTML() using libxml_get_errors()

    Retrieve the error by using libxml_get_errors() perform logging or return the list of issues to the caller.

    $html = $this->curl_get_contents($url, $lang);
            /**
             * parsing starts here:.
             */
            $doc = new DOMDocument();
    
            $libxml_previous_state = libxml_use_internal_errors(true);
            $doc->loadHTML('<?xml encoding="utf-8" ?>'.$html);
    
            //catch possible errors due to empty or malformed HTML
            Log::warning(libxml_get_errors())
    
            libxml_clear_errors();
            // restore previous state
            libxml_use_internal_errors($libxml_previous_state);
    

    Using Log::warning(libxml_get_errors()) is not compatible with PHP 5.6

    opened by shweshi 3
  • Package not working on all website

    Package not working on all website

    The package seems not to work with some website. for exemple this one : https://www.udemy.com/formation-a-la-photographie-pour-les-debutants/

    I tried with other package and it seems to be a 403 error ... any clue on this ?

    closed 
    opened by vtibo 3
  • Log errors from DOMDocument::loadHTML() using libxml_get_errors()

    Log errors from DOMDocument::loadHTML() using libxml_get_errors()

    added fourth argument which can be used to pass additional options to LoadHTML() method, including options for suppressing warnings and errors; loadHTML() second argument is 0 (LIBXML_ERR_NONE flag) #64

    opened by alinmiron 2
  • Update OpenGraph.php

    Update OpenGraph.php

    using try...catch wasn't best idea since if there are a lot of DOMDocument::loadHTML() everything gets really slow.

    the libxml_use_internal_errors(true) indicates that you're going to handle the errors and warnings ourselves and so they don'to mess up the output / slow down things.

    This is not the same as the @ operator. The warnings get collected behind the scenes and afterwards you can retrieve them by using libxml_get_errors() in case you wish to perform logging or return the list of issues to the caller.

    Whether or not you're using the collected warnings you should always clear the queue by calling libxml_clear_errors().

    opened by alinmiron 2
  • Add get_meta_value

    Add get_meta_value

    Some meta tag may use value instead of content property

    Added get_meta_value to handle this kind of case, also when both content nor value property is present, will return null

    Example case of meta value property: Medium read time meta data

    <meta data-rh="true" name="twitter:label1" value="Reading time" />
    <meta data-rh="true" name="twitter:data1" value="3 min read" />
    
    opened by gavinclive 1
  • throwing an exception when the url returns 404 -breaking test.

    throwing an exception when the url returns 404 -breaking test.

    Describe the bug A clear and concise description of what the bug is.

    To Reproduce Steps to reproduce the behavior: Run a test from cli that calls... $data = OpenGraph::fetch($url, true); // where url returns a 404 error. See error: shweshi\OpenGraph\Exceptions\FetchException. The requested URL returned error: 404 Not Found

    Expected behavior I would have expected the error to have been failed gracefully, returning the 404 message to the calling method.

    Desktop (please complete the following information):

    • OS: MacOS with Docker/Laradock
    • Browser n/a
    • Version current/latest

    Additional context I'm actually calling it with... but still not getting past the fetch error thrown.

    try {
                $data = OpenGraph::fetch($url, true);
            } catch (shweshi\OpenGraph\Exceptions\FetchException $e) {
                $message = $e->getMessage();
                $data = $e->getData();
            }
    
    help wanted good first issue hacktoberfest 
    opened by jayenne 1
  • Support for CURL proxy

    Support for CURL proxy

    Suggestion: I think, it will be a great addition if you add support for CURL requests through proxy, passed as parameter to fetch()

    Reason: Sometimes, URL access is blocked or is slow from the server's country/location. In that case it's easier to setup/use a proxy server instead of creating a custom php solution from scratch.

    enhancement help wanted good first issue 
    opened by sdiama 1
  • Add option to fetch open graph data from html string

    Add option to fetch open graph data from html string

    In my case I fetch page html for further use (searching for other data) but also need to get open graph data, I could use this package if it allowed to pass html string instead of url.

    enhancement help wanted good first issue 
    opened by vedmant 1
  • include Title tag too?

    include Title tag too?

    Although not technically a meta tag, the title tag would be a handy addition as it is an arbitraty informative label too.

    With a tiny addition between the $metadata decleration the $tags as $tag loop to create a$metadata['title'] key val pair, one could add the given title too.

            if($allMeta){
                $title = $doc->getElementsByTagName('title');
                $metadata['title'] = $title->length > 0 ? $title->item(0)->textContent : null ;
            }
    

    By putting it here, should there be a metata tag called title too, it would override this value for the preffered one.

    opened by jayenne 3
  • Problem to get meta image

    Problem to get meta image

    Good Morning,

    I'm writing you because I have had a bug when obtaining the openGraph of a url, it does not get the image because it has escaped characters and it is not validated.

    When using openGraph there are certain urls from which the image is not obtained correctly, and it is because a decode of the image should be added in the verify_image_url function.

    Page example: https://www.forbes.com/sites/forbescoachescouncil/2017/04/19/networking-or-job-boards-nine-strategies-to-find-your-next-role/

    Image url: https://thumbor.forbes.com/thumbor/fit-in/1200x0/filters%3Aformat%28jpg%29/https%3A%2F%2Fblogs-images.forbes.com%2Fforbescoachescouncil%2Ffiles%2F2017%2F04%2FNetworking-or-Job-Boards-Nine-Strategies-To-Land-Your-Next-Role.jpg

    Solution: $url = urldecode ($url);

    Thanks in advance,

    Mirian

    enhancement help wanted good first issue hacktoberfest 
    opened by MirianBebee 1
Releases(V1.1.2)
Owner
Shashi Prakash Gautam
Software Developer
Shashi Prakash Gautam
kreatinc project (laravel graph Facebook api)

kreatinc project (laravel graph Facebook api)

Useef 4 Nov 4, 2022
My aim is to make a complete website that should have all the essential parts a website should have.

Gaming-Ninja I aim to make a complete website that should have all the essential parts a website should have. https://gamingninja-3399.000webhostapp.c

Anand Jaiswar 3 Nov 23, 2022
An Easy, Customizable & Open Source Robux Rewards Website Made With Laravel

RbxDream - Robux Earning Rewards Website Coming Soon Current repo not stable. This is an open source Robux rewards site. Understanding Core Concepts T

Underground 3 Feb 15, 2022
Laravel package that converts your application into a static HTML website

phpReel Static Laravel Package phpReel Static is a simple Laravel Package created and used by phpReel that converts your Laravel application to a stat

phpReel 16 Jul 7, 2022
this package makes laravel website a progressive web application.

Laravel PWA You can follow this video tutorial as well for installation. Installation Install the package by the following command, composer require l

Shailesh Ladumor 86 Dec 16, 2022
This Laravel 8 package makes it possible for you to set your website in "Under Construction" mode.

Laravel Under Construction This Laravel package makes it possible to set your website in "Under Construction" mode. Only users with the correct 4 digi

Lars Janssen 571 Dec 18, 2022
A Laravel URL Shortener package that provides URL redirects with optionally protected URL password, URL expiration, open limits before expiration

A Laravel URL Shortener package that provides URL redirects with optionally protected URL password, URL expiration, open limits before expiration, ability to set feature activation dates, and click tracking out of the box for your Laravel applications.

YorCreative 53 Jan 4, 2023
Save Model is a Laravel package that allows you to save data in the database in a new way.

Save Model is a Laravel package that allows you to save data in the database in a new way. No need to worry about $guarded and $fillable properties in the model anymore. Just relax an use Save Model package.

Laratips 27 Mar 2, 2022
A laravel package to handle sanitize process of model data to create/update model records.

Laravel Model UUID A simple package to sanitize model data to create/update table records. Installation Require the package using composer: composer r

null 66 Sep 19, 2022
Laravel Grid is a package that helps you display table data.

Laravel Grid Laravel Grid is a package that helps you display table data. I could not find package that would satisfy my needs so I decided to write o

null 9 Nov 29, 2022
Smeify is a Stable Automated Solution for Airtime and Data businesses in Nigeria, this package helps you integrate smeify easily into your laravel application.

Smeify is a Stable Automated Solution for Airtime and Data businesses in Nigeria, this package helps you integrate smeify easily into your laravel application.

Ogundiran Adewale Charles 2 Jul 27, 2022
Laravel package to normalize your data before saving into the database.

This package helps you normalize your data in order to save them into the database. The Goal is to having separate classes that handle the data normalization, and thus can be tested independently.

Nicolas Widart 11 Apr 21, 2021
Laravel 5.* package to easily introduce a transformation layer for your data

Laraformer Laraformer is a laravel 5.* package that lets you easily introduce a transformation layer for your data. Laraformer (originated from Larave

Kamran Ahmed 30 Oct 19, 2022
A laravel package to access data from the Strava API.

Laravel Strava Package A laravel package to access data from the Strava API. Compatible with Laravel 5.0 and above. Table of Contents Strava Access Cr

Richie 52 Nov 15, 2022
Laravel package to work with geospatial data types and functions.

Laravel Spatial Laravel package to work with geospatial data types and functions. For now it supports only MySql Spatial Data Types and Functions. Sup

Tarfin 47 Oct 3, 2022
A PHP package that provides common Data and Value Objects, that are Laravel castable.

Common Casts A PHP package that provides common Data and Value Objects, that are Laravel castable. Installation composer require juststeveking/common-

Steve McDougall 2 Sep 21, 2022
A package that makes it easy to have the `artisan make:` commands open the newly created file in your editor of choice.

Open On Make A package that makes it easy to have the artisan make: commands open the newly created file in your editor of choice. Installation compos

Andrew Huggins 94 Nov 22, 2022
Flow package to synchronize metadata and binary data of imported Neos.Media assets

Wwwision.AssetSync Flow package to synchronize metadata and resources of imported Neos.Media assets Installation Install this package via: composer re

Bastian Waidelich 5 Feb 7, 2022
An easy way to get vendor and package data from Packagist via API calls

Laravel Packagist Laravel Packagist (LaravelPackagist) is a package for Laravel 5 to interact with the packagist api quickly and easily. Table of cont

Jeremy Kenedy 5 Jul 18, 2022