Objective

In this article I will go through the steps of pulling the latest news from a news API, compose a video summary of these news using a vertical video template that can be used for Instagram posts.

This demo can be useful for media publishers to automate the publication of their latest news in social media.

This is an example of the resulting video:

You can download the final JSON that generates the video above.

The source of news

For this demo I will use NewsAPI.org as my source of news. NewsAPI.org is an amazing service that indexes thousands of articles every day from tens of countries and in different languages, allowing you to query this database by keywords, countries, topics, etc.

As an example, you can get the latest news about Tesla, or what has been published about a particular keyword in the last 4 years in the main media outlets. For this demo, I will pull the latest science news in the United States.

If you are a media publisher you can pull your own news feed from your database or use your own MRSS feed.

Setup the project

This demonstration will be built with some plain PHP. This will be a really short demonstration, but it would be easy to translate the code to other languages like Node JS or Python. The idea is to show how easy it is to get started with programmatic video creation.

If you are interested in going deeper on creating video editing scripts with PHP you can check my other articles on PHP.

The only thing I need is to install the JSON2Video PHP SDK:

composer require json2video/json2video-php-sdk

This will create the vendor directory and the composer.json and composer.lock files in the current directory.

The PHP script starts loading the SDK and defining the API Keys:

<?php

    require "vendor/autoload.php";

    use JSON2Video\Scene;
    use JSON2Video\Movie;

    $json2video_apikey = "---- YOUR JSON2VIDEO API KEY HERE ----";
    $newsapi_apikey = "---- YOUR NEWSAPI API KEY HERE ----";

Curate the input for the video

Getting the news feed from NewsAPI.org

The service has a free tier of 100 calls per day that is good enough for the purpose of this demo. You can get an API Key from its website.

To get the latest science news in the United States, I used the following API request:

https://newsapi.org/v2/top-headlines?category=science&country=us&apiKey=[[YOUR_API_KEY]]

And this is the response I got:

{
    "status": "ok",
    "totalResults": 32,
    "articles": [
        {
            "source": {
                "id": null,
                "name": "Sky.com"
            },
            "author": "Sky",
            "title": "NASA plans to take International Space Station out of orbit in January 2031 by crashing it into 'spacecraft cemetery' - Sky News",
            "description": "",
            "url": "https://news.sky.com/story/nasa-plans-to-take-international-space-station-out-of-orbit-in-january-2031-by-crashing-it-into-spacecraft-cemetery-12530194",
            "urlToImage": "https://e3.365dm.com/21/11/1600x900/skynews-international-space_5573335.jpg?20211105222328",
            "publishedAt": "2022-02-01T11:44:23Z",
            "content": "NASA has published plans for the future of the International Space Station which could see the 444,615kg structure taken out of orbit in January 2031 and crashed into a \"spacecraft cemetery\".\r\nThe la\u2026 [+2724 chars]"
        },
        {
            "source": {
                "id": null,
                "name": "Florida Today"
            },
            "author": "Emre Kelly, Florida Today",
            "title": "SpaceX launches into stunning skies on fifth try, lands at Cape Canaveral - Florida Today",
            "description": "A SpaceX Falcon 9 rocket finally broke a scrub streak on Monday, vaulting an Earth observation satellite into skies so clear that the entire process from launch to landing back at Cape Canaveral was visible.",
            "url": "https://www.floridatoday.com/story/tech/science/space/2022/01/31/spacex-launches-into-stunning-skies-fifth-try-lands-florida/9292806002/",
            "urlToImage": "https://www.gannett-cdn.com/presto/2022/02/01/PBRE/e66157e7-590f-405e-8203-77f16cd48baa-Monday_SpaceX_Launch_as_Seen_from_Port_St._John_8.jpg?auto=webp&crop=4560,2565,x0,y80&format=pjpg&width=1200",
            "publishedAt": "2022-02-01T04:41:03Z",
            "content": "Space is important to us\u00a0and that\u2019s why we're\u00a0working to bring you top coverage of the\u00a0industry and Florida launches. Journalism like this takes time and resources. Please support it with a subscript\u2026 [+2830 chars]"
        },
        {
            "source": {
                "id": null,
                "name": "SciTechDaily"
            },
            "author": null,
            "title": "James Webb Space Telescope Commissioning Set to Begin - SciTechDaily",
            "description": "Following Webb\u2019s arrival at its orbital destination around Lagrange Point 2 (L2) on January 24, the mission operations team began working its way through a critical series of steps: powering on all the science instruments, turning off heaters to begin a long \u2026",
            "url": "https://scitechdaily.com/james-webb-space-telescope-commissioning-set-to-begin/",
            "urlToImage": "https://scitechdaily.com/images/James-Webb-Space-Telescope-Primary-Mirror-in-Space.gif",
            "publishedAt": "2022-02-01T04:23:31Z",
            "content": "Credit: NASA\u2019s Goddard Space Flight Center\r\nFollowing Webb\u2019s arrival at its orbital destination around Lagrange Point 2 (L2) on January 24, the mission operations team began working its way through a\u2026 [+1845 chars]"
        },
        {
            "source": {
                "id": null,
                "name": "KTVZ"
            },
            "author": "KTVZ news sources",
            "title": "'The Bulge' is back: USGS scientists detect renewed uplift near South Sister volcano - KTVZ",
            "description": "SISTERS, Ore. (KTVZ) -- Some two decades after first drawing widespread attention, a small (but detectable by satellite) uplift near the South Sister volcano is making news once again, with a quicker rate of rising ground than seen for years, accompanied by s\u2026",
            "url": "https://ktvz.com/news/central-oregon/2022/01/31/the-bulge-is-back-usgs-scientists-detect-renewed-uplift-near-south-sister-volcano/",
            "urlToImage": "https://ktvz.b-cdn.net/2022/01/South-Sister-uplift-USGS.jpg",
            "publishedAt": "2022-02-01T01:33:10Z",
            "content": "SISTERS, Ore. (KTVZ) -- Some two decades after first drawing widespread attention, a small (but detectable by satellite) uplift near the South Sister volcano is making news once again, with a quicker\u2026 [+2380 chars]"
        },
        {
            "source": {
                "id": null,
                "name": "Newser"
            },
            "author": "Bob Cronin",
            "title": "Crew Simulates Stress of Mars Trip - Newser",
            "description": "Four volunteers are sealed in a structure at Johnson Space Center",
            "url": "https://www.newser.com/story/316342/nasa-crew-has-begun-simulated-mars-trip.html",
            "urlToImage": "https://img2-azrcdn.newser.com/image/1396347-12-20220131192959.jpeg",
            "publishedAt": "2022-02-01T01:00:00Z",
            "content": "(Newser)\r\nA NASA crew has begun a 45-day trip to Mars, all in a habitat on the ground at the Johnson Space Center in Houston. A volunteer crew of four launched the simulated journey Friday, CNN repor\u2026 [+998 chars]"
        },
        {
            "source": {
                "id": "ars-technica",
                "name": "Ars Technica"
            },
            "author": "Jennifer Ouellette",
            "title": "Physicists discover that clouds of ultracold atoms can form \u201cquantum tornadoes\u201d - Ars Technica",
            "description": "The effect is similar to the macroscale phenomenon of Kelvin-Helmholtz clouds.",
            "url": "https://arstechnica.com/science/2022/01/physicists-discover-that-clouds-of-ultracold-atoms-can-form-quantum-tornadoes/",
            "urlToImage": "https://cdn.arstechnica.net/wp-content/uploads/2022/01/quantumtornadoTOP-760x380.jpg",
            "publishedAt": "2022-02-01T00:56:15Z",
            "content": "Enlarge/ (l-r) A quantum gas appears first as an elongated rod. As it rotates, it becomes helical, then it breaks up into blobs, each a swirling mass. Between the blobs tiny vortices appear in a regu\u2026 [+6324 chars]"
        },
        {
            "source": {
                "id": null,
                "name": "WESH Orlando"
            },
            "author": "Scott Heidler",
            "title": "Lift off! SpaceX Falcon 9 takes off after multiple delays - WESH 2 Orlando",
            "description": "The rocket is waiting and ready on the cape after three consecutive bad weather delays.",
            "url": "https://www.wesh.com/article/spacex-finally-set-to-take-off/38944222",
            "urlToImage": "https://kubrick.htvapps.com/vidthumb/7c673370-0eed-4a90-bd16-60bc3bc7b13b/7c673370-0eed-4a90-bd16-60bc3bc7b13b_image.jpg?crop=1.00xw:1.00xh;0,0&resize=1200:*",
            "publishedAt": "2022-01-31T23:23:00Z",
            "content": "PORT CANAVERAL, Fla. \u2014A SpaceX Falcon 9 rocket lifted off Monday evening after multiple attempts, with delays including three consecutive bad weather days.\r\nSunday's scrub was caused by a cruise ship\u2026 [+1277 chars]"
        },
        {
            "source": {
                "id": null,
                "name": "Phys.Org"
            },
            "author": "Frits Sweijen",
            "title": "The universe is in much sharper focus with new algorithms and supercomputers - Phys.org",
            "description": "With new algorithms and supercomputers, an incredibly detailed radio map of the universe has been created. Now astronomers can look at radio data of galaxies with much more precision. This research was published in Nature Astronomy by Leiden University Ph.D. \u2026",
            "url": "https://phys.org/news/2022-01-universe-sharper-focus-algorithms-supercomputers.html",
            "urlToImage": "https://scx2.b-cdn.net/gfx/news/2022/the-universe-is-in-muc.jpg",
            "publishedAt": "2022-01-31T21:07:22Z",
            "content": "With new algorithms and supercomputers, an incredibly detailed radio map of the universe has been created. Now astronomers can look at radio data of galaxies with much more precision. This research w\u2026 [+3946 chars]"
        },
        {
            "source": {
                "id": null,
                "name": "Phys.Org"
            },
            "author": "Science X staff",
            "title": "What the rise of oxygen on early Earth tells us about life on other planets - Phys.org",
            "description": "When did the Earth reach oxygen levels sufficient to support animal life? Researchers from McGill University have discovered that a rise in oxygen levels occurred in step with the evolution and expansion of complex, eukaryotic ecosystems. Their findings repre\u2026",
            "url": "https://phys.org/news/2022-01-oxygen-early-earth-life-planets.html",
            "urlToImage": "https://scx2.b-cdn.net/gfx/news/2022/what-the-rise-of-oxyge.jpg",
            "publishedAt": "2022-01-31T21:06:50Z",
            "content": "When did the Earth reach oxygen levels sufficient to support animal life? Researchers from McGill University have discovered that a rise in oxygen levels occurred in step with the evolution and expan\u2026 [+4242 chars]"
        },
        {
            "source": {
                "id": null,
                "name": "New York Times"
            },
            "author": "Dennis Overbye",
            "title": "The Milky Way: An Electrifying View - The New York Times",
            "description": "A new radio-wave image of the center of our galaxy reveals all the forms of frenzy that a hundred million or so stars can get up to.",
            "url": "https://www.nytimes.com/2022/01/31/science/milky-way.html",
            "urlToImage": "https://static01.nyt.com/images/2022/01/28/science/00SCI-OUTTHERE-meerkat1/merlin_200918067_b51c4e5a-333d-4f98-afd8-4a640f65e23a-facebookJumbo.jpg",
            "publishedAt": "2022-01-31T20:51:59Z",
            "content": "The Milky Ways disc, where most of the stars and exoplanets reside, appears in the image as a ragged horizontal streak. A dense blob of energy in the middle of the streak marks the spot where lurks a\u2026 [+1256 chars]"
        },
        {
            "source": {
                "id": null,
                "name": "NASA"
            },
            "author": null,
            "title": "NASA Asteroid Tracking System Now Capable of Full Sky Search - NASA",
            "description": "The NASA-funded ATLAS has reached a new milestone by becoming the first survey capable of searching the entire dark sky every 24 hours for near-Earth objects that could pose a future impact hazard to Earth.",
            "url": "https://www.nasa.gov/feature/nasa-asteroid-tracking-system-now-capable-of-full-sky-search/",
            "urlToImage": "http://www.nasa.gov/sites/default/files/thumbnails/image/atlas_header_image.png",
            "publishedAt": "2022-01-31T19:51:02Z",
            "content": null
        },
        {
            "source": {
                "id": "the-verge",
                "name": "The Verge"
            },
            "author": "Loren Grush",
            "title": "China releases video of spacecraft orbiting Mars for Lunar New Year - The Verge",
            "description": "The China National Space Administration released a video selfie of its Mars orbiter, Tianwen-1, for the Chinese Lunar New Year, showing the vehicle as it zooms around Mars with the planet in the background.",
            "url": "https://www.theverge.com/2022/1/31/22910712/china-tianwen-1-spacecraft-mars-orbiter-selfie-video",
            "urlToImage": "https://cdn.vox-cdn.com/thumbor/yHnJjEHL0Rg4r4SkCkZXa4jFVcw=/0x55:2506x1367/fit-in/1200x630/cdn.vox-cdn.com/uploads/chorus_asset/file/23207729/Screen_Shot_2022_01_31_at_12.31.34_PM.png",
            "publishedAt": "2022-01-31T18:49:45Z",
            "content": "Ride along in the Red Planets orbit\r\nImage: Screenshot from Tianwen-1 video on China Xianhu News\r\nChinas first Mars orbiter, Tianwen-1, is showing off its journey around the Red Planet in a newly rel\u2026 [+2028 chars]"
        },
        {
            "source": {
                "id": null,
                "name": "Spaceflight Now"
            },
            "author": null,
            "title": "SpaceX preps for launch of spy satellite payload from California this week \u2013 Spaceflight Now - Spaceflight Now",
            "description": null,
            "url": "https://spaceflightnow.com/2022/01/31/spacex-preps-for-launch-of-spy-satellite-payload-from-california-this-week/",
            "urlToImage": null,
            "publishedAt": "2022-01-31T18:48:43Z",
            "content": "The official patch for the NROL-87 mission. Credit: NRO\r\nThe first launch of the year from Vandenberg Space Force Base in California, set for Wednesday afternoon, will send a payload into orbit for t\u2026 [+3887 chars]"
        },
        {
            "source": {
                "id": null,
                "name": "Live Science"
            },
            "author": "Andrew May",
            "title": "What is the grandfather paradox? - Livescience.com",
            "description": "Can you go back in time and kill an ancestor without creating a logical paradox? Surprisingly, the answer may be yes.",
            "url": "https://www.livescience.com/grandfather-paradox",
            "urlToImage": "https://cdn.mos.cms.futurecdn.net/QaubgzASAEUHo5owbeZnhE-1200-80.jpg",
            "publishedAt": "2022-01-31T18:01:31Z",
            "content": "The grandfather paradox is a self-contradictory situation that arises in some time travel\r\n scenarios that is illustrated by the impossible scenario in which a person travels back in time only to kil\u2026 [+9323 chars]"
        },
        {
            "source": {
                "id": null,
                "name": "Futurism"
            },
            "author": null,
            "title": "Astronaut Warns Tom Cruise About Appalling Smell on Space Station - Futurism",
            "description": "NASA astronaut Victor Glover sat down for a chat with Hollywood actor Tom Cruise to prepare him for what it's really like to spend time on board the ISS.",
            "url": "https://futurism.com/the-byte/astronaut-tom-cruise-smell-space-station",
            "urlToImage": "https://wp-assets.futurism.com/2022/01/astronaut-tom-cruise-smell-space-station.jpg",
            "publishedAt": "2022-01-31T17:13:35Z",
            "content": "\"When you go into the module that has the lifting, the strength training equipment, that's also where the bathroom is.\"\r\nEau de Space\r\nNASA astronaut Victor Glover sat down for a chat with Hollywood \u2026 [+2419 chars]"
        },
        {
            "source": {
                "id": null,
                "name": "Space.com"
            },
            "author": "Brandon Specktor",
            "title": "Ancient solar storm smashed Earth at the wrong part of the sun's cycle \u2014 and scientists are concerned - Space.com",
            "description": "The 9,200-year-old storm left researchers with a stark conclusion: We are not ready for the next one.",
            "url": "https://www.space.com/ancient-solar-storm-solar-minimum",
            "urlToImage": "https://cdn.mos.cms.futurecdn.net/kCMCNHYyxXVrJHVG2DG6wW-1200-80.jpg",
            "publishedAt": "2022-01-31T16:03:07Z",
            "content": "An extremely powerful solar storm pummeled our planet 9,200 years ago, leaving permanent scars on the ice buried deep below Greenland and\u00a0Antarctica.\r\nA new study of those ancient ice samples has fou\u2026 [+4083 chars]"
        },
        {
            "source": {
                "id": "newsweek",
                "name": "Newsweek"
            },
            "author": "Orlando Jenkinson",
            "title": "Wooly Mammoth De-extinction Scientist Reveals Plan To Create 'Arctic Elephant' - Newsweek",
            "description": "George Church, from the Harvard Medical School, founded a company to bring the wooly mammoth back to life in 2021.",
            "url": "https://www.newsweek.com/wooly-mammoth-de-extinction-scientist-plan-create-arctic-elephant-1674509",
            "urlToImage": "https://d.newsweek.com/en/full/1977809/baby-mammoth.jpg",
            "publishedAt": "2022-01-31T15:20:20Z",
            "content": "A scientist who plans to bring the wooly mammoth\u2014or at least its genes\u2014back from extinction has revealed details about creating an \"Arctic elephant.\"\r\nMammoths mostly died out around 10,000 years ago\u2026 [+6261 chars]"
        },
        {
            "source": {
                "id": null,
                "name": "New York Times"
            },
            "author": "William J. Broad",
            "title": "Fermat's Theorem: The Texas Oil Heir Who Took on Math's Impossible Dare - The New York Times",
            "description": "James M. Vaughn Jr., wielding a fortune, argues that he brought about the Fermat breakthrough after the best and brightest had failed for centuries to solve the puzzle.",
            "url": "https://www.nytimes.com/2022/01/31/science/james-vaughn-fermat-theorem.html",
            "urlToImage": "https://static01.nyt.com/images/2022/01/28/science/00sci-vaughn-promo/00sci-vaughn-promo-facebookJumbo.jpg",
            "publishedAt": "2022-01-31T15:11:56Z",
            "content": "In September 1981, Mr. Vaughn funded the worlds first big conference on the Fermat riddle. It took place at Endicott House, an M.I.T. meeting center near Boston set in a French manor-style mansion on\u2026 [+1969 chars]"
        },
        {
            "source": {
                "id": "cnn",
                "name": "CNN"
            },
            "author": "Katie Hunt, CNN",
            "title": "Rings in 'tree stump' crater found on Mars illuminate red planet's past climate - CNN",
            "description": "A Martian crater that looks a lot like a tree stump from above is shedding light on the history of the red planet.",
            "url": "https://www.cnn.com/2022/01/31/world/tree-stump-crater-mars-scn/index.html",
            "urlToImage": "https://cdn.cnn.com/cnnnext/dam/assets/220131115618-tree-stump-crater-mars-scn-super-tease.jpg",
            "publishedAt": "2022-01-31T14:44:00Z",
            "content": "(CNN)At first glance, it looks like a tree stump but the circular feature in a newly released image captured by the ExoMars orbiter is actually an ice-rich crater on Mars.\r\nJust as a tree's concentri\u2026 [+750 chars]"
        },
        {
            "source": {
                "id": null,
                "name": "Daily Mail"
            },
            "author": "Sam Tonkin",
            "title": "Why Uranus and Neptune are different shades of blue - Daily Mail",
            "description": "Uranus has a haze layer in its atmosphere that is roughly double the thickness of Neptune, giving it the much paler colour, according to researchers led by the University of Oxford.",
            "url": "https://www.dailymail.co.uk/sciencetech/article-10459589/Why-Uranus-Neptune-different-shades-blue.html",
            "urlToImage": "https://i.dailymail.co.uk/1s/2022/01/31/13/53586419-0-image-a-14_1643636631378.jpg",
            "publishedAt": "2022-01-31T14:13:09Z",
            "content": "They are the far-away 'ice giants' of our solar system that to the naked eye each glow a slightly different shade of blue.\r\nBut now the mystery of why Uranus appears paler than Neptune's deeper, coba\u2026 [+4873 chars]"
        }
    ]
}

This response includes 14 articles from different media publishers published in the last few hours, including the article headline, the source name, the publication date and a URL to the article's main image.

This is just what I need to create my news video summary! ✌️

This is the PHP code to query the API:

   // Get the news from the API
    $api_url = "https://newsapi.org/v2/top-headlines?category=science&country=us&apiKey=" . $newsapi_apikey;
    $api_response = file_get_contents($api_url);
    $api_json = json_decode($api_response, true);
    if (!$api_json) die("Error reading NewsAPI");

Fixing minor issues

Reviewing the NewsAPI output, I notice that I need to transform a few things:

Therefore, I will create a new array just with the info I need:

    // Parse the response and create a final JSON
    $articles = [];
    $num_articles = 0;

    foreach ($api_json["articles"] as $article) {

        // Bypass any URL that includes ".gif"
        if (strpos($article["urlToImage"], ".gif")!==false) continue;

        // Remove anything from " - " and after
        $source_position = strpos($article["title"], " - ");
        if ($source_position!==false) $headline = substr($article["title"], 0, $source_position);
        else $headline = $article["title"];

        // Convert to human readible date
        $human_date = date("M jS", strtotime($article["publishedAt"]));

        // Add a new article to the list
        $articles[] = [
            "headline" => $headline,
            "date" => $human_date,
            "image" => $article["urlToImage"],
            "source" => $article["source"]["name"]
        ];

        // Limit the number of articles in the list
        $num_articles++;
        if ($num_articles>3) break;
    }

Create the video

Now that I have all the content I need, we can create the video movie.

Movie object setup

First, create a Movie object and setup it up:

   // Create a new movie
    $movie = new Movie;

    // Set your API key
    // Get your free API key at https://json2video.com
    $movie->setAPIKey($json2video_apikey);

    // Set a project ID
    $movie->project = "tutorial";

    // Set movie quality: low, medium, high
    $movie->quality = "high";

    // Set movie dimensions for an Instagram story
    $movie_width = 607;
    $movie_height = 1080;
    $margin = 50;

    $movie->width = $movie_width;
    $movie->height = $movie_height;

I define three variables ($movie_width, $movie_height and $margin) that will be used later on in the code. $movie_width and $movie_height are the video dimensions. $margin is the margin used to position the elements in the scene.

Instragram story videos must have 9:16 ratio with a maximum of 1920 pixels in height. However, I will use a smaller size (still 9:16) of 607 x 1080.

Add an intro bumper

The video will start with a bumper showing my acme brand: "SCIENCE TODAY":

   // Intro bumper
    $intro = new Scene;

    $intro->addElement([
        "type" => "text",
        "template" => "basic/022",
        "settings" => [
            "slide" => "right"
        ],
        "items" => [
            [
                "text" => "SCIENCE",
                "font-size" => 50,
                "background-color" => "#FF0000",
                "color" => "#FFFFFF"
            ],
            [
                "text" => "TODAY",
                "font-size" => 50,
                "background-color" => "#FFFFFF",
                "color" => "#000000"
            ]
        ],
        "x" => $margin,
        "y" => $movie_height/2
    ]);

    $movie->addScene($intro);

Add the articles

Now, I can create an scene for each article, adding the article's image as a background (with pan left or right effect), the headline at the bottom, the publisher and date at the top-left and a voice-over reading the headline:

    // Create an scene for each article

    foreach ($articles as $key => $article) {
        
        $scene =  new Scene;

        // Add the article's image as background with pan effect
        $scene->addElement([
            "type" => "image",
            "src" => $article["image"],
            "scale" => [
                "height" => $movie_height
            ],
            "x" => intval(-($movie_height*16/9)/2 + $movie_width/2),
            "zoom" => 5,
            "pan" => ($key % 2) ? "right" : "left"
        ]);

        // Add the headline at the bottom using the basic/021 template
        $scene->addElement([
            "type" => "text",
            "template" => "basic/021",
            "settings" => [
                "left-bar-color" => "#FFFFFF",
                "vertical-align" => "bottom"
            ],
            "items" => [
                [
                    "text" => $article["headline"],
                    "background-color" => "#000000",
                    "color" => "#FFFFFF",
                    "font-size" => 40
                ]
            ],
            "width" => intval($movie_width - $margin*2),
            "x" => intval($margin),
            "y" => intval(-$margin)
        ]);

        // Add the publisher name and date at the top-left
        // keeping a margin
        $scene->addElement([
            "type" => "text",
            "template" => "basic/022",
            "settings" => [
                "slide" => "right"
            ],
            "items" => [
                [
                    "text" => $article["source"],
                    "font-size" => 20,
                    "background-color" => "#FF0000",
                    "color" => "#FFFFFF"
                ],
                [
                    "text" => $article["date"],
                    "font-size" => 20,
                    "background-color" => "#FFFFFF",
                    "color" => "#000000"
                ]
            ],
            "x" => $margin,
            "y" => $margin
        ]);

        // Generate the voice over from the headline
        // using the male voice en-US-GuyNeural
        $scene->addElement([
            "type" => "voice",
            "voice" => "en-US-GuyNeural",
            "text" => $article["headline"],
            "start" => 0.5,
            "extra-time" => 0.5
        ]);

        // Add the scene into the movie
        $movie->addScene($scene);
    }

Add a closing scene

I will close my video with a black scene showing "Powered by JSON2Video.com".

    // Add a closing scene
    $closing = new Scene;
    $closing->addElement([
        "type" => "text",
        "template" => "basic/008",
        "items" => [
            [
                "text" => "Powered by JSON2Video.com",
                "font-size" => 20
            ]
        ],
        "x" => $margin,
        "y" => $movie_height/2
    ]);
    $movie->addScene($closing);

Add a background music

Finally, I will add a background music across the movie:

    // Add a background music to the movie
    $movie->addElement([
        "type" => "audio",
        "src" => "https://assets.json2video.com/assets/audios/news-opening-01.mp3",
        "volume" => 0.2
    ]);

Render the movie

The last step is to send the movie to be rendered by JSON2Video and wait until the movie is ready:

    // Call JSON2Video API and start rendering the movie
    $movie->render();

    // Wait for the render to finish
    $movie->waitToFinish();

The final result

The final PHP script code is:

<?php

require "vendor/autoload.php";

use JSON2Video\Scene;
use JSON2Video\Movie;

$json2video_apikey = "--- YOUR JSON2VIDEO API KEY ----";
$newsapi_apikey = "---- YOUR NEWSAPI.ORG API KEY ----";

// Get the news from the API
$api_url = "https://newsapi.org/v2/top-headlines?category=science&country=us&apiKey=" . $newsapi_apikey;
//$api_response = file_get_contents($api_url);
$api_response = file_get_contents("news2.json");
$api_json = json_decode($api_response, true);
if (!$api_json) die("Error reading NewsAPI");

// Parse the response and create a final JSON
$articles = [];
$num_articles = 0;

foreach ($api_json["articles"] as $article) {

    // Bypass any URL that includes ".gif"
    if (strpos($article["urlToImage"], ".gif")!==false) continue;

    // Remove anything from " - " and after
    $source_position = strpos($article["title"], " - ");
    if ($source_position!==false) $headline = substr($article["title"], 0, $source_position);
    else $headline = $article["title"];

    // Convert to human readible date
    $human_date = date("M jS", strtotime($article["publishedAt"]));

    // Add a new article to the list
    $articles[] = [
        "headline" => $headline,
        "date" => $human_date,
        "image" => $article["urlToImage"],
        "source" => $article["source"]["name"]
    ];

    // Limit the number of articles in the list
    $num_articles++;
    if ($num_articles>3) break;
}


// Create a new movie
$movie = new Movie;

// Set your API key
// Get your free API key at https://json2video.com
$movie->setAPIKey($json2video_apikey);

// Set a project ID
$movie->project = "tutorial";

// Set movie quality: low, medium, high
$movie->quality = "high";

// Set movie dimensions for an Instagram story
$movie_width = 607;
$movie_height = 1080;
$margin = 50;

$movie->width = $movie_width;
$movie->height = $movie_height;


// Intro bumper
$intro = new Scene;

$intro->addElement([
    "type" => "text",
    "template" => "basic/022",
    "settings" => [
        "slide" => "right"
    ],
    "items" => [
        [
            "text" => "SCIENCE",
            "font-size" => 50,
            "background-color" => "#FF0000",
            "color" => "#FFFFFF"
        ],
        [
            "text" => "TODAY",
            "font-size" => 50,
            "background-color" => "#FFFFFF",
            "color" => "#000000"
        ]
    ],
    "x" => $margin,
    "y" => $movie_height/2
]);

$movie->addScene($intro);


// Create an scene for each article

foreach ($articles as $key => $article) {
    
    $scene =  new Scene;

    // Add the article's image as background with pan effect
    $scene->addElement([
        "type" => "image",
        "src" => $article["image"],
        "scale" => [
            "height" => $movie_height
        ],
        "x" => intval(-($movie_height*16/9)/2 + $movie_width/2),
        "zoom" => 5,
        "pan" => ($key % 2) ? "right" : "left"
    ]);

    // Add the headline at the bottom using the basic/021 template
    $scene->addElement([
        "type" => "text",
        "template" => "basic/021",
        "settings" => [
            "left-bar-color" => "#FFFFFF",
            "vertical-align" => "bottom"
        ],
        "items" => [
            [
                "text" => $article["headline"],
                "background-color" => "#000000",
                "color" => "#FFFFFF",
                "font-size" => 40
            ]
        ],
        "width" => intval($movie_width - $margin*2),
        "x" => intval($margin),
        "y" => intval(-$margin)
    ]);

    // Add the publisher name and date at the top-left
    // keeping a margin
    $scene->addElement([
        "type" => "text",
        "template" => "basic/022",
        "settings" => [
            "slide" => "right"
        ],
        "items" => [
            [
                "text" => $article["source"],
                "font-size" => 20,
                "background-color" => "#FF0000",
                "color" => "#FFFFFF"
            ],
            [
                "text" => $article["date"],
                "font-size" => 20,
                "background-color" => "#FFFFFF",
                "color" => "#000000"
            ]
        ],
        "x" => $margin,
        "y" => $margin
    ]);

    // Generate the voice over from the headline
    // using the male voice en-US-GuyNeural
    $scene->addElement([
        "type" => "voice",
        "voice" => "en-US-GuyNeural",
        "text" => $article["headline"],
        "start" => 0.5,
        "extra-time" => 0.5
    ]);

    // Add the scene into the movie
    $movie->addScene($scene);
}

// Add a closing scene
$closing = new Scene;
$closing->addElement([
    "type" => "text",
    "template" => "basic/008",
    "items" => [
        [
            "text" => "Powered by JSON2Video.com",
            "font-size" => 20
        ]
    ],
    "x" => $margin,
    "y" => $movie_height/2
]);
$movie->addScene($closing);


// Add a background music to the movie
$movie->addElement([
    "type" => "audio",
    "src" => "https://assets.json2video.com/assets/audios/news-opening-01.mp3",
    "volume" => 0.2
]);

// Call JSON2Video API and start rendering the movie
$movie->render();

// Wait for the render to finish
$movie->waitToFinish();


And the resulting video is:

Credits

Published on January 12th, 2022

Author
David Bosch
David Bosch David is an experienced engineer now co-Founder of JSON2Video.