NewsApi.org

Thank you for visiting our news api page. The following article is open source code for working with https://www.newsapi.org  in php.

the following code is the source of our test page. located here.  http://www.newsverifier.com/test

Here is a brief description of the code we have created so far…

All of this software and source code is released by Jeffrey Nelson owner at newsverifier.com as open source. There is no implied warranty and this code may or may not work for you. You can copy and use it modify it etc. If you do though please comment here to let us know the changes. I think my coding is a bit sloppy and I am certain there is a better way.

<?php

$json_string = ‘https://newsapi.org/v2/top-headlines?country=us&apiKey=YOUR API KEY’;
$jsondata = file_get_contents($json_string);

//first I create a jsoniterator to deal with string we are receiving from newsapi.

$jsonIterator = new RecursiveIteratorIterator(
new RecursiveArrayIterator(json_decode($jsondata, TRUE)),
RecursiveIteratorIterator::SELF_FIRST);

//next I define the variables that will display our information on the page.

$id = ‘id’;
$name = ‘name’;
$author = ‘author’;
$title = ‘title’;
$description = ‘description’;
$url = ‘url’;
$urlToImage = ‘urlToIamge’;
$publishedAt = ‘publishedAt’;
$content = ‘content’;

//then I create a loop to deal with the information in a logical way.

foreach ($jsonIterator as $key => $val) {

//here I am setting my control variable to prevent over looping or mismatched information..

$i = 0;

//here I am looping through all of the values of our json string that has been iterated.

if(is_array($val)) {
echo “\n”;
} else {
if($key == “id”)
{$id = $val;}
if($key == “name”)
{$name = $val;}
if($key == “author”)
{$author = $val;}
if($key == “title”)
{$title = $val;}
if($key == “description”)
{$description = $val;}
if($key == “url”)
{$url = $val;}
if($key == “urlToImage”)
{$urlToImage = $val;}
if($key == “publishedAt”)
{$TimeStamp = $val;}

//here I am setting my control variable to prevent over looping or mismatched information..

if($key == “content”)
{$content = $val; $i++;}

//here I am using the control variable that i have created to define what the output will look like…
if($content != ‘content’)
{
$mycontent = ‘<center><table border=”0″ width=”50%”><tr><td><a href=”‘.$url.'”><font size=”+3″>’.$title.'</a></font></td></tr><tr><td><table><tr><td><img src=”‘.$urlToImage.'” width=”750″ height=”500″></td><td valign=”top”><font size=”+1″><b>’.$content.'<p><a href=”‘.$url.'”>Read this article here</a></b></font></td></tr></table></td></tr><tr><td>Time Stamp ‘.$TimeStamp.'</td></tr></table></center></p><p>&nbsp;<p>&nbsp;’;
}
if($i == 1)
{
//this is where I diplay the desired output information for the current news.
echo $mycontent;
}
}
}

?>

We will be developing a new wordpress plugin that is open source as part of this system. Please give us feedback or suggestions.