Want to get just two object in json - php

I am trying to make a code verifier with the following code. I've looked at the answers in StackOverflow but couldn't get the right result.
The code is working fine but I want to echo just two value.
validate.php page code is here:
if(isset($apKey) && isset($code)) {
$en = new En();
$Key = $apKey;
$Codes = $code;
if($Key == null || $Codes == null) {
echo json_encode(['data' => 'No Key or code found, Please try again']);
exit;
}
$response = $en->validate($Key,$Codes);
$result = json_decode($response);
$elements = json_encode(['data' => $result]);
echo $elements;
exit;
}
echo json_encode(['data' => 'No Key or code found, Please try again']);
exit;
Now I am trying to check this validate page results using this code:
$siteurl = urlencode($_SERVER['SERVER_NAME']);
$arrContextOptions = array(
"ssl" => array(
"verify_peer" => false,
"verify_peer_name" => false
)
);
$file = file_get_contents('http://www.validates.com/validate.php?code=' . $check , false, stream_context_create($arrContextOptions));
$checks = json_decode($file, true);
$elements = $checks['data'];
echo print_r($elements);
So the results something like this:
Array
(
[buyer] => abcd
)
So what I want to do. I want to echo just buyer and error message after this code: $checks = json_decode($file, true);
The error result is here:
{"data":{"error":404,"description":"No sale belonging to the current user found with that code"}}
Like for example:
if(buyer){echo 'true';}
if(error message){echo 'error';}

I guess you can check with array_key_exists if there is error. You can do something like this:
$checks = json_decode($file, true);
$data = $checks['data'];
if (array_key_exists("error", $data))
echo $data["description"];
else
echo $data["buyer"];

Related

facebook pagination using next() URL error

I am working on facebook pagination, I have searched but didn't get relevant answer.
First I am fetching 10 result and after that onclick function I want to fetch next 10 results for this I am passing -
[paging] =>
Array
(
[previous] => https://graph.facebook.com/v2.9/....D&__previous=1
[next] => https://graph.facebook.com/........
)
as parameter,I also tried passing next URL as parameter but still it is not working, if I pass $feedEdge as associated I am getting response as null,below is my code
$response = self::$_FBINSTANCE->get('/me/feed?fields=id,message&limit=' . $_pagination->limit);
if(empty($_nextFeed)){
$feedEdge = $response->getGraphEdge();
$nextFeed = $response->getGraphEdge()->getMetaData();
}else{
$feedEdge=$response->next($_nextFeed);
$nextFeed = $response->getGraphEdge()->getMetaData();
}
$result = array();
foreach ($feedEdge as $status) {
$result[] = $status->asArray();
}
return array(
'result' => $result,
'totalRows' => $totalCount,
'nextFeed' => $nextFeed
);
using v2.9 version, what parameter I should pass for $response->next(); help me if I am wrong .
I found solution for this question...
If any one is trying for same try below code.
$result = array();
if(empty($_nextFeed)){
$response = $fb->get('/me/feed?fields=id,message&limit=' . $_pagination->limit);
$feedEdge = $response->getGraphEdge();
foreach ($feedEdge as $status) {
$result[] = $status->asArray();
}
$nextFeed = $response->getGraphEdge()->getMetaData();
}else{
//to get until time stamp form next url
$nextURl=parse_url($_nextFeed['paging']['next']);
parse_str($nextURl['query'], $URL);
$response = $fb->get('/me/feed?fields=id,message&limit='.(($_pagination->limit)+1).'&until='.$URL['until']);
$feedEdge = $response->getGraphEdge();
foreach ($feedEdge as $status) {
$result[] = $status->asArray();
}
//because result repeats last array of previous request
array_splice($result,0,1);
$nextFeed = $response->getGraphEdge()->getMetaData();
}
return array(
'result' => $result,
'totalRows' => $totalCount,
'nextFeed' => $nextFeed
);
It works :)

JSON encode an array with file_get_contents

I'm trying to figure out how to encode the following:
$data[] = '';
//check if real player
if($steam_name != null){
$data['valid'] = true;
$data['url'] = "http://api.steampowered.com/ISteamUser/ResolveVanityURL/v0001/?key=key&vanityurl=$steam_name";
echo json_encode($data, file_get_contents($data->url));
}else{
$data['valid'] = false;
echo json_encode($data);
}
I understand how to get the data, but it seems to not be sending through.
Thanks!
My attempt as per answer below. This does not work:
$data[] = '';
//check if real player
if($steam_name != null){
$data['valid'] = true;
$url = 'http://api.steampowered.com/ISteamUser/ResolveVanityURL/v0001/?';
$params = [
'key' => 'key',
'vanityurl' => $steam_name,
];
$data['url'] = $url . http_build_query($params);
echo json_encode($data);
}else{
$data['valid'] = false;
echo json_encode($data);
}
You should be using http_build_query() to accomplish that.
$url = 'http://api.steampowered.com/ISteamUser/ResolveVanityURL/v0001/?';
$params = [
'key' => 'abc123',
'vanityurl' => $steam_name,
];
$data['url'] = $url . http_build_query($params);
That will handle the proper encoding for the parameters.
Additionally, $data is an array here, you can't call it like an object in your file_get_contents call. I'm surprised you aren't getting an exception. Also, json_encode doesn't accept parameters like that. Try this:
// Store the API response in your data array
$data['response'] = file_get_contents($data['url']);
// Return it so you can use it
return json_encode($data);
If the response is JSON, you can decode it:
$data['response'] = json_decode(file_get_contents($data['url']));

Invalid Array from json_decode()

I have a PHP file that grabs a .txt file and decodes the JSON to push the user's e-mail and name entry to my campaign monitor database. The JSON is wonky because new entries are added with a ][ as seen in this example:
[{"email":"drake.scott#test.com","createdate":"2016-03-23 10:44:52","from_email":null,"from_liked_pageid":null,"source":"direct","bonus_entry_url":"\/xxxbyn\/h1lvw5","entry_url":"https:\/\/admin.woobox.com\/manage\/offers\/entries\/20160314-1\/tu%2BcJmnsgyUxE7HM9BCqnRjnza27dGIdr%2BHymHrFmFoprsRgkhZradPrTJ5s18p6ewxYeOOKLpObd%2FWGAS%2BDRw%3D%3D","shareurl":"http:\/\/woobox.com\/qbxbyn\/h1lvw5","picked":"0","actionbutton":"","custom_3_first":"drake","custom_3_last":"scott","custom_4":"4146583264","fullname":"drake scott","id":"vvvbyn"}]
[{"email":"john.roberts#test.com","createdate":"2016-03-23 10:44:52","from_email":null,"from_liked_pageid":null,"source":"direct","bonus_entry_url":"\/xxx\/h1lvw5","entry_url":"https:\/\/admin.woobox.com\/manage\/offers\/entries\/20160314-1\/tu%2BcJmnsgyUxE7HM9BCqnRjnza27dGIdr%2BHymHrFmFoprsRgkhZradPrTJ5s18p6ewxYeOOKLpObd%2FWGAS%2BDRw%3D%3D","shareurl":"http:\/\/woobox.com\/vvvbyn\/h1lvw5","picked":"0","actionbutton":"","custom_3_first":"john","custom_3_last":"adams","custom_4":"4146585018","fullname":"john adams","id":"vvvbyn"}]
The problem I am having right now is uploading the entries to my database. I have managed to strip the ][ and doing a var_dump($content); shows a valid JSON string. However, doing var_dump($user) gives me 0 array(0) { }.
The entries will not upload to my database because there is essentially nothing in my array. Can anyone give me some insight on how to proceed?
<?php
require_once 'csrest_general.php';
require_once 'csrest_subscribers.php';
$auth = array(
'api_key' => 'xxxxxxxxxx');
$wrap = new CS_REST_Subscribers('xxxxxxxxxx', $auth);
$url = 'http://www.mywebsite.com/sweeps/test.txt';
$content = file_get_contents($url);
$content = str_replace('}][{', '},{', $content);
$tmp = explode('][', $content);
foreach ($tmp as $json_part) {
$user = json_decode('['.rtrim(ltrim($json_string, '['), ']').']', true);
$result = $wrap->add(array(
'EmailAddress' => $user->email,
'Name' => $user->fullname,
'Resubscribe' => true
));
}
if($result->was_successful()) {
echo "Subscribed with code ".$result->http_status_code;
}
else {
echo "failed";
var_dump($result->response);
var_dump($user);
}
?>
There are multiple JSON objects concatenated in the file. The easiest way to make the JSON valid is to create an array:
$content = str_replace('][', ',', $content);
$users = json_decode($content, true);
Then you have a multi-dimensional array with multiple users that you will need to decide what you want from it:
print_r($users);
foreach($users as $user) {
echo $user['email'] . "\n";
}

PHP Server Error 500 when Echo doesnt exist?

My php code works fine when I add in an echo in a certain spot, but when I remove the simple echo "hello"; line it doesnt load the php page and it just shows Server Error 500.
The following code works:
require 'steam.php';
$steam = new steam();
$api = "FC1D74A835829EB99A571235A499638A";
$query = 'ari9';
$communityID = $steam->getID($query, $api);
$userInfo = $steam->getUserInfo($communityID, $api);
echo "hello";
$info = array(
'communityID' => $communityID,
'steamID' => $steam->$convertToSteamID($communityID),
'personaname' => $userInfo['personaname'],
'profileurl' => $userInfo['profileurl'],
'lastlogoff' => $userInfo['lastlogoff'],
);
foreach ($info as $key => $value) {
if (strlen($value)===0) {
$info[$key] = false;
}
echo $key." -> ".$value."<br>";
}
echo json_encode($info);
And the following code does not work:
require 'steam.php';
$steam = new steam();
$api = "FC1D74A835829EB99A571235A499638A";
$query = 'ari9';
$communityID = $steam->getID($query, $api);
$userInfo = $steam->getUserInfo($communityID, $api);
$info = array(
'communityID' => $communityID,
'steamID' => $steam->$convertToSteamID($communityID),
'personaname' => $userInfo['personaname'],
'profileurl' => $userInfo['profileurl'],
'lastlogoff' => $userInfo['lastlogoff'],
);
foreach ($info as $key => $value) {
if (strlen($value)===0) {
$info[$key] = false;
}
echo $key." -> ".$value."<br>";
}
echo json_encode($info);
and the following code does not work:
require 'steam.php';
$steam = new steam();
$api = "FC1D74A835829EB99A571235A499638A";
$query = 'ari9';
$communityID = $steam->getID($query, $api);
$userInfo = $steam->getUserInfo($communityID, $api);
$info = array(
'communityID' => $communityID,
'steamID' => $steam->$convertToSteamID($communityID),
'personaname' => $userInfo['personaname'],
'profileurl' => $userInfo['profileurl'],
'lastlogoff' => $userInfo['lastlogoff'],
);
foreach ($info as $key => $value) {
if (strlen($value)===0) {
$info[$key] = false;
}
echo $key." -> ".$value."<br>";
}
echo json_encode($info);
echo "Hello";
The first piece of code has the echo on line 9 and the second one is identical to the first except the echo on line 9 is removed. I'm puzzled by this.
The issue is that this $steam->$convertToSteamID is looking for a function with the name of whatever that variables value is. The reason you get the 500 when there isn't an echo is because when you send the echo that serves a 200. There should be events in your log displaying the error. You can't have 2 status codes though on a page.
So just change your function call to:
$steam->convertToSteamID
and you should be fine.

Find Method Returning False

I am trying to execute a find in my script, but I believe my condition is returning false. I am trying to execute a find and pull all records that match the given value in my $data variable. I have tried to compare the BranchLicense.RegionCode to $data but no luck. I have also tried to compare it the _Session['Auth']['User']['region_code']. The $data variable is returning the correct value but the script does not return the proper records. What am I doing wrong here? Here is my code.
//echo '<pre>'; print_r($_SESSION); echo '</pre>';
//$this->loadModel('AuthAcl.Users');
$data = $_SESSION['Auth']['User']['region_code'];
//$data = $this->Users->find('all');
$new = $this->BranchLicense->find('all', array(
'conditions' => array('BranchLicense.RegionCode' == $data)));
die(debug($new));
$this->layout = 'default';
//$this->set('branchLicenses', $this->BranchLicense->find('all', array(
//'conditions' => array('BranchLicense.RegionCode' === '$data'))));
Try as follows-
$new = $this->BranchLicense->find('all', array(
'conditions' => array('BranchLicense.RegionCode' => $data)));
die(debug($new));

Categories