Match IDs taken from 2 inputs (JSON) and do something if positive - php

Here's a sample of a JSON entry output from Feedbin's entries.json:
[
{
"id": 2077,
"title": "Objective-C Runtime Releases",
"url": "http:\/\/mjtsai.com\/blog\/2013\/02\/02\/objective-c-runtime-releases\/",
"author": "Michael Tsai",
"content": "<p><a href=\"https:\/\/twitter.com\/bavarious\/status\/297851496945577984\">Bavarious<\/a> created a <a href=\"https:\/\/github.com\/bavarious\/objc4\/commits\/master\">GitHub repository<\/a> that shows the differences between versions of <a href=\"http:\/\/www.opensource.apple.com\/source\/objc4\/\">Apple\u2019s Objective-C runtime<\/a> that shipped with different versions of Mac OS X.<\/p>",
"summary": "Bavarious created a GitHub repository that shows the differences between versions of Apple\u2019s Objective-C runtime that shipped with different versions of Mac OS X.",
"published": "2013-02-03T01:00:19.000000Z",
"created_at": "2013-02-04T01:00:19.127893Z"
}
]
Here's my function which authenticates with Feedbin's API, retrieves the JSON document, and prints title and URL for the first 5 results.
<?php
// JSON URL which should be requested
$json_url = 'https://api.feedbin.me/v2/entries.json';
$username = 'username'; // authentication
$password = 'password'; // authentication
// Initializing curl
$ch = curl_init( $json_url );
// Configuring curl options
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_USERPWD => $username . ":" . $password // authentication
);
// Setting curl options
curl_setopt_array( $ch, $options );
// Getting results
$result = curl_exec($ch); // Getting JSON result string
$cache_feedbin = '/BLAHBLAH/'.sha1($json_url).'.json';
if(file_exists($cache_feedbin) && filemtime($cache_feedbin) > time() - 1000){
// if a cache file newer than 1000 seconds exist, use it
$data_feedbin = file_get_contents($cache_feedbin);
} else {
$data_feedbin = $result;
file_put_contents($cache_feedbin, $data_feedbin);
}
foreach (array_slice(json_decode($data_feedbin), 0, 5) as $obj) {
$feedbin_title = $obj->title;
$feedbin_url = $obj->url;
echo '<li>', $feedbin_title, '</li>';
}
?>
It works like a charm. What I'd love to try is mixing this with unread_entries.json, which retuns an array of entry_ids of unread items. Something like:
[4087,4088,4089,4090,4091,4092,4093,4094,4095,4096,4097]
My goal is: check within the foreach which IDs match with the IDs of unread items taken from unread_entries.json. For the IDs that match (so, unread items) do nothing, for ALL THE OTHERS, display an image which says "READ".

BONUS ROUND:
Updated example to include a function for caching JSON requests:
define('CACHE_PATH', '/tmp'); // Might want to change this
define('CACHE_SECS', 1000);
define('API_USERNAME', 'username');
define('API_PASSWORD', 'password');
$entries = fetchJSON('https://api.feedbin.me/v2/entries.json', API_USERNAME, API_PASSWORD, CACHE_SECS);
$unread_msgs = fetchJSON('https://api.feedbin.me/v2/unread_entries.json', API_USERNAME, API_PASSWORD, CACHE_SECS);
foreach ($entries as $obj) {
$is_read = !in_array($obj->id, $unread_msgs); // Read if not present in unread
$feedbin_title = $obj->title;
$feedbin_url = $obj->url;
$output = '<li><a href="'.$feedbin_url.'">'. $feedbin_title;
if ($is_read) {
$output .= ' <img src="icon-read.png" title="READ" />';
}
$output .= '</a></li>';
echo $output;
}
/** Return a JSON decoded object/array */
function fetchJSON($json_url, $username = null, $password = null, $cache_secs = null) {
$cache_file = CACHE_PATH.'/'.sha1($json_url).'.json';
$data = null;
// Check if we need to request new content
if (!$cache_secs || !file_exists($cache_file) || filemtime($cache_file) < time() - $cache_secs) {
// Initializing curl
$ch = curl_init( $json_url );
// Configuring curl options
$options = array(
CURLOPT_RETURNTRANSFER => true,
);
// If username given add to curl opts
if (!empty($username)) {
$options[CURLOPT_USERPWD] = $username . ":" . $password;
}
// Setting curl options
curl_setopt_array( $ch, $options );
// Getting results
$data = curl_exec($ch); // Getting JSON result string
curl_close($ch);
if ($cache_secs) {
file_put_contents($cache_file, $data);
}
} else {
// Got data from the cache
$data = file_get_contents($cache_file);
}
return !empty($data) ? json_decode($data) : null;
}

$ids = [4087,4088,4089,4090,4091,4092,4093,4094,4095,4096,4097];
$id = 4087;
if (isset($ids[$id]) )
{
echo "do something\n";
}
else
{
echo "do something else\n";
}

Related

JSON increment doesn't work

I am working on a JSON file in which I want to increment instead of overwriting the data. However I cannot seem to do this (since it keeps on overwriting instead of adding data with an incremented ID).
The code underneath is: database_json.php (as u can see I include it in saveJson.php)
$databaseFile = file_get_contents('json_files/database.json');
$databaseJson = json_decode($databaseFile, true);
$database = $databaseJson['data'];
the below is the code of the file saveJson.php contains the following code:
// below starts a new page, the page that submits the form called saveJson.php
include_once('database_json.php');
$data = $_POST;
//Setup an empty array.
$errors = array();
if (isset($data)) {
$newExerciseData = $data;
$exerciseArray = $data['main_object'];
$databaseFile = 'json_files/database.json';
$textContent = file_get_contents($databaseFile);
$database = json_decode($textContent, true);
if ($data['id'] === 'new') {
if (count($database['data']) == 0) {
$ID = 0;
}
else {
$maxID = max($database['data']);
$ID = ++$maxID["id"];
}
$newJsonFile = 'jsonData_' . $ID . '.json';
$newJsonFilePath = 'json_files/' . $newJsonFile;
//Create new database exercise_txt
$newArrayData = array(
'id' => $ID,
// a lot of variables that aren't related to the problem
);
$database['data'][] = $newArrayData;
file_put_contents($databaseFile, json_encode($database, JSON_UNESCAPED_UNICODE, JSON_PRETTY_PRINT));
file_put_contents($newJsonFilePath, json_encode($newExerciseData, JSON_UNESCAPED_UNICODE, JSON_PRETTY_PRINT));
}
else {
$index = array_search((int) $_POST['id'], array_column($database['data'], 'id'));
$correctJsonFile = 'json_files/jsonData_' . $_POST['id'] . '.json';
$newJsonFile = 'jsonData_' . $_POST['id'] . '.json';
$newJsonFilePath = 'json_files/' . $newJsonFile;
//Create new database exercise_txt
$newArrayData2 = array(
'id' => (int) $_POST['id'],
// more not related to problem variables
);
$database['data'][$index] = $newArrayData2;
file_put_contents($databaseFile, json_encode($database, JSON_UNESCAPED_UNICODE));
file_put_contents($newJsonFilePath, json_encode($newExerciseData, JSON_UNESCAPED_UNICODE));
}
echo json_encode($newExerciseData, JSON_UNESCAPED_UNICODE);
}
so, what I wish for: To increment the IDs and NOT to overwrite the data.
I already did some research and didn't find any useful information besides this --> Auto increment id JSON, but to me it looks like I have the same principle applied.

PHP MySQL Dialogflow

I'm setting up a chatbot (dialogflow) with a PHP webhook
What I want to do is to take the user input to query a MySQL table and pass the result back to the dialogflow API
So far I succeeded with passing a text string back to the API, but I don't understand how to query the database and pass the result back to the dialogflow API
I'll appreciate your help with this
I've used the API format from the dialogflow docs here
This is what I have
<?php
$method = $_SERVER['REQUEST_METHOD'];
if($method == 'POST') {
$requestBody = file_get_contents('php://input');
$json = json_decode($requestBody);
$text = $json->result->parameters->cities;
$conn = mysqli_connect("xxx", "xxx", "xxx", "xxx");
$sql = "SELECT * FROM exampletable LIKE '%".$_POST["cities"]."%'";
$result = mysqli_query($conn, $sql);
$emparray = array();
while($row =mysqli_fetch_assoc($result)) {
$emparray[] = $row;
}
$speech = $emparray;
$response->speech = $speech;
$response->displayText = $speech;
$response->source = "webhook";
echo json_encode(array($response,$emparray));
else
{
echo "Method not allowed";
}
?>
Thankyou
whenever the webhook gets triggered you need to listen to actions from JSON responses,
from the action made the switch case of actions
index.php
<?php
require 'get_enews.php';
function processMessage($input) {
$action = $input["result"]["action"];
switch($action){
case 'getNews':
$param = $input["result"]["parameters"]["number"];
getNews($param);
break;
default :
sendMessage(array(
"source" => "RMC",
"speech" => "I am not able to understand. what do you want ?",
"displayText" => "I am not able to understand. what do you want ?",
"contextOut" => array()
));
}
}
function sendMessage($parameters) {
header('Content-Type: application/json');
$data = str_replace('\/','/',json_encode($parameters));
echo $data;
}
$input = json_decode(file_get_contents('php://input'), true);
if (isset($input["result"]["action"])) {
processMessage($input);
}
?>
get_enews.php
<?php
function getNews($param){
require 'config.php';
$getNews="";
$Query="SELECT link FROM public.news WHERE year='$param'";
$Result=pg_query($con,$Query);
if(isset($Result) && !empty($Result) && pg_num_rows($Result) > 0){
$row=pg_fetch_assoc($Result);
$getNews= "Here is details that you require - Link: " . $row["link"];
$arr=array(
"source" => "RMC",
"speech" => $getNews,
"displayText" => $getNews,
);
sendMessage($arr);
}else{
$arr=array(
"source" => "RMC",
"speech" => "No year matched in database.",
"displayText" => "No year matched in database.",
);
sendMessage($arr);
}
}
?>
So when the action gets caught it will get executed and goes in the getNews($param); function here I am getting year as a response from the user in my case and I am executing the query in the database and giving back a response from the database.

How to get "metric" and "element" names for PHP - Adobe Analytics

I am pulling a report using the Adobe API from Omniture.
Here is the full script :
<?php
include_once('/path/SimpleRestClient.php');
// Date
$end_date = date("Y-m-d",strtotime("-1 days"));
$start_date = date("Y-m-d",strtotime("-8 days"));
// Location of the files exported
$adobe_file = '/path/Adobe_'.$end_date.'.csv';
// List creation that will be updated with the fields and be put into my CSV file
$list = array
(
array('lasttouchchannel', 'product','visits','CTR(Clicks/PageViews)') // headers // ADD or DELETE metrics #
);
function GetAPIData($method, $data)
{
$username = "XXXX";
$shared_secret = "XXXX";
$postURL = "https://api3.omniture.com/admin/1.4/rest/?method=";
// Nonce is a simple unique id to each call to prevent MITM attacks.
$nonce = md5(uniqid(php_uname('n'), true));
// The current timestamp in ISO-8601 format
$nonce_ts = date('c');
/* The Password digest is a concatenation of the nonce, it is timestamp and your password
(from the same location as your username) which runs through SHA1 and then through a base64 encoding */
$digest = base64_encode(sha1($nonce . $nonce_ts . $shared_secret));
$rc = new SimpleRestClient();
$rc -> setOption(CURLOPT_HTTPHEADER, array("X-WSSE: UsernameToken Username=\"$username\", PasswordDigest=\"$digest\", Nonce=\"$nonce\", Created=\"$nonce_ts\""));
//var_dump($o);
$rc -> postWebRequest($postURL .$method, $data);
return $rc;
}
$method = 'Report.Queue';
$data ='
{
"reportDescription":
{
"reportSuiteID":"XXXX",
"dateFrom":"'.$start_date.'",
"dateTo":"'.$end_date.'",
"metrics":[{"id":"visits"},{"id":"instances"},{"id":"pageviews"}],
"elements":[{"id":"lasttouchchannel","top":"50000"}]
}
}';
/*
"date":"'.$date.'",
"dateTo":"'.$date.'",
"dateFrom":"'.$start_date.'",
"dateTo":"'.$end_date.'",
*/
$rc=GetAPIData($method, $data);
if($rc -> getStatusCode() == 200) // status code 200 is for 'ok'
{
$counter = 0;
do
{
if($counter>0){sleep($sleep = 120);}
$return = GetAPIData('Report.Get', $rc->getWebResponse());
$counter++;
}while($return -> getStatusCode() == 400 && json_decode($return->getWebResponse())->error == 'report_not_ready'); // status code 400 is for 'bad request'
//
$json=json_decode($return->getWebResponse());
foreach ($json->report->data as $el)
{
echo $el->name.":".$el->counts[0].":".$el->counts[1]."\n";
// Adding the data in the CSV file without overwriting the previous data
array_push($list, array($el->name, $el->name, $el->counts[0], ($el->counts[1])/($el->counts[2])));
}
}
else
{
echo "Wrong";
}
$fp = fopen($adobe_file, 'w');
foreach ($list as $fields)
{
// Save the data into a CSV file
fputcsv($fp, $fields);
}
fclose($fp);
?>
How can I get the names of the metrics and elements in order to use them in this script? There is no way. I searched with all the possible tags on google and nothing worked !
I need the metrics and elements for this part of the code :
$data ='
{
"reportDescription":
{
"reportSuiteID":"XXXX",
"dateFrom":"'.$start_date.'",
"dateTo":"'.$end_date.'",
"metrics":[{"id":"visits"},{"id":"instances"},{"id":"pageviews"}],
"elements":[{"id":"lasttouchchannel","top":"50000"}]
}
}';
I cannot find 'date' as an element which is crucial. I cannot find all the other metrics as well. In Google Analytics we had this link :
Google Analytics Query
but in Adobe there is not any. I want something like that :
"metrics":[{"id":"instances"},{"id":"impressions"}],
"elements":[{"id":"date","top":"50000"}]
You would json_decode() as $data contains a JSON string. For example:
$data ='
{
"reportDescription":
{
"reportSuiteID":"XXXX",
"dateFrom":"'.$start_date.'",
"dateTo":"'.$end_date.'",
"metrics":[{"id":"visits"},{"id":"instances"},{"id":"pageviews"}],
"elements":[{"id":"lasttouchchannel","top":"50000"}]
}
}';
$json = json_decode($data, true);
echo $json['reportDescription']['dateFrom'];
print_r($json['reportDescription']['metrics']);

Downloading images from rets feed using phprets

I am trying to use PHPRETS to download RETS FEED Data and Images, I am successful in downloading data as CSV but, though images are created in the image folder properly, the size of each image is zero. I am attaching the code I am using here, please help me so that I can download images properly.
<?php
$rets_login_url = "http://retsgw.flexmls.com:80/rets2_0/Login";
$rets_username = "**********";
$rets_password = "**********";
// use http://retsmd.com to help determine the SystemName of the DateTime field which
// designates when a record was last modified
$rets_modtimestamp_field = "LIST_87";
// use http://retsmd.com to help determine the names of the classes you want to pull.
// these might be something like RE_1, RES, RESI, 1, etc.
$property_classes = array("B");
// DateTime which is used to determine how far back to retrieve records.
// using a really old date so we can get everything
$previous_start_time = "1980-01-01T00:00:00"; require_once("lib/phrets.php");
// start rets connection
$rets = new phRETS;
// only enable this if you know the server supports the optional RETS feature called 'Offset'
$rets->SetParam("offset_support", true);
echo "+ Connecting to {$rets_login_url} as {$rets_username}<br>\n";
$connect = $rets->Connect($rets_login_url, $rets_username, $rets_password);
if ($connect) {
echo " + Connected<br>\n";
}
else {
echo " + Not connected:<br>\n";
print_r($rets->Error());
exit;
}
foreach ($property_classes as $class) {
echo "+ Property:{$class}<br>\n";
$file_name = strtolower("property_{$class}.csv");
$fh = fopen($file_name, "w+") or die("Can't open file");
$fields_order = array();
$query = "({$rets_modtimestamp_field}={$previous_start_time}+)";
// run RETS search
echo " + Resource: Property Class: {$class} Query: {$query}<br>\n";
$search = $rets->SearchQuery("Property", $class, $query, array('Limit' => 1000));
$get_id = $_REQUEST['LIST_1'];
if ($rets->NumRows($search) > 0) {
// print filename headers as first line
$fields_order = $rets->SearchGetFields($search);
fputcsv($fh, $fields_order);
// process results
while ($record = $rets->FetchRow($search)) {
$this_record = array();
foreach ($fields_order as $fo) {
if ($fo == 'LIST_1') {
$photos = $rets->GetObject("Property", "Photo", $record[$fo], "*", 1);
foreach ($photos as $photo) {
if ($photo['Success'] == true) {
file_put_contents("photos/{$photo['Content-ID']}-{$photo['Object-ID']}.jpg", $photo['Data']);
}
}
}
$this_record[] = $record[$fo];
}
fputcsv($fh, $this_record);
}
}
echo " + Total found: {$rets->TotalRecordsFound($search)}<br>\n";
$rets->FreeResult($search);
fclose($fh);
echo " - done<br>\n";
}
echo "+ Disconnecting<br>\n";
$rets->Disconnect();
?>
You have this line. It is returning the image URL, not the binary image data.
$photos = $rets->GetObject("Property", "Photo", $record[$fo], "*", 1);
The fifth argument should be a 0.
$photos = $rets->GetObject("Property", "Photo", $record[$fo], "*", 0);
According to the PHRETS documentation, a 1 returns the image URL and a 0 returns the binary image data.
https://github.com/troydavisson/PHRETS/wiki/GetObject

Dealing with Instagram APIs (JSON + PHP)

I'm new to PHP and I can't figure out how to deal with Instagram APIs in order to (for example) extract a list of links to the standard resolution images by recent 3 items published by the user_id 3.
Here's what I created till now:
<?php
function get_instagram($user_id,$count)
{
$user_id = '3';
$count = '3';
$url = 'https://api.instagram.com/v1/users/'.$user_id.'/media/recent/?access_token=13137.f59def8.1a759775695548999504c219ce7b2ecf&count='.$count;
$jsonData = $json_decode((file_get_contents($url)));
$data = $jsonData->data;
$result = '<ul>';
foreach ($data as $key => $value) {
$result .= '<li><a href='.$value->link.' ><img src="'.$value->images->standard_resolution->url.'" width="70" height="70" /></a></li> ';
}
$result .= '</ul>';
return $result;
}
The result is a blank page though.. can you help me?
You need to echo or do something with the returned data (Also you have a rouge $ in front of your json_decode function)
Try this:
<?php
function get_instagram($user_id=15203338,$count=6,$width=190,$height=190){
$url = 'https://api.instagram.com/v1/users/'.$user_id.'/media/recent/?access_token=13137.f59def8.1a759775695548999504c219ce7b2ecf&count='.$count;
// Also Perhaps you should cache the results as the instagram API is slow
$cache = './'.sha1($url).'.json';
if(file_exists($cache) && filemtime($cache) > time() - 60*60){
// If a cache file exists, and it is newer than 1 hour, use it
$jsonData = json_decode(file_get_contents($cache));
} else {
$jsonData = json_decode((file_get_contents($url)));
file_put_contents($cache,json_encode($jsonData));
}
$result = '<div id="instagram">'.PHP_EOL;
foreach ($jsonData->data as $key=>$value) {
$result .= "\t".'<a class="fancybox" data-fancybox-group="gallery"
title="'.htmlentities($value->caption->text).' '.htmlentities(date("F j, Y, g:i a", $value->caption->created_time)).'"
style="padding:3px" href="'.$value->images->standard_resolution->url.'">
<img src="'.$value->images->low_resolution->url.'" alt="'.$value->caption->text.'" width="'.$width.'" height="'.$height.'" />
</a>'.PHP_EOL;
}
$result .= '</div>'.PHP_EOL;
return $result;
}
echo get_instagram();
?>
With $value->location->name
If you want to check its empty and if it is then dont show it but also want to append a string onto it if it is set you would do something like:
$location = (!empty($value->location->name))?'#'.$value->location->name:null;
Then use $location to echo where you want it.
I've extended the selected answer by writing a small script that can be used a boilerplate for anyone trying this.
It's setup with all the variables and starts with basic markup. Using selectors from Instagrams API docs you can build onto its output as needed.
This is built to be used specifically with WordPress with one small tweak to the image size conditional it can be used in any PHP application.
<?php
function instagram($count = 10, $width = 640, $height = 640) {
$user_id = 123456789;
$access_token = '123456789';
$size = wp_is_mobile() ? 'low_resolution' : 'standard_resolution';
$url = 'https://api.instagram.com/v1/users/'.$user_id.'/media/recent/?access_token='.$access_token.'&count='.$count;
$cache_location = './'.sha1($url).'.json';
$cache_time = '-1 hour';
if (file_exists($cache_location) && filemtime($cache_location) > strtotime($cache_time)) {
// If a cache file exists, and it is newer than 1 hour, use it
$jsonData = json_decode(file_get_contents($cache_location));
} else {
$jsonData = json_decode((file_get_contents($url)));
file_put_contents($cache_location,json_encode($jsonData));
}
foreach ($jsonData->data as $key=>$value) {
echo '<div>';
echo '<img src="'.$value->images->$size->url.'"/>';
echo '</div>';
}
}
Basic Usage
<?php echo instagram(); ?>
Advanced Usage
<?php echo instagram($count = 1, $width = 100, $height = 100); ?>
Github Repo
Welp, This was working a week ago, but now, it gives me a PHP error:
"Message: Trying to get property of non-object"
on the line with the foreach statement: foreach ($jsonData->data as $key=>$value)
Turns out my JSON feed was actually corrupted, the captions to some of my instagrams were missing, so I had to add an if empty statement. I also am using a different method now, curious on your thoughts, works great!
<?php
function fetchData($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
$result = fetchData("https://api.instagram.com/v1/users/USER ID HERE/media/recent/?access_token=ACCES TOKEN HERE&count=14");
$cache = './instagram.json';
if(file_exists($cache) && filemtime($cache) > time() - 60*60){
// If a cache file exists, and it is newer than 1 hour, use it
$instaData = json_decode(file_get_contents($cache));
} else {
$instaData = json_decode((file_get_contents($result)));
file_put_contents($cache,json_encode($instaData));
}
foreach ($instaData->data as $post) {
if(empty($post->caption->text)) {
// Do Nothing
}
else {
echo '<a class="instagram-unit" target="blank" href="'.$post->link.'">
<img src="'.$post->images->low_resolution->url.'" alt="'.$post->caption->text.'" width="100%" height="auto" />
<div class="instagram-desc">'.htmlentities($post->caption->text).' | '.htmlentities(date("F j, Y, g:i a", $post->caption->created_time)).'</div></a>';
}
}
?>

Categories