cakephp 3 - passing dates with json - json

Cakephp3, I am passing data to another page using Json, my issue seems to be on my new page where my created date is passed as a sting , and displays like '2016-05-16T17:21:10+0000' . How do i format that string to be left with '2016-05-16' ? I've tried setting it as a date, i tried using the i18nFormat with no success.
$http = new Client();
$response = $http->get('http://localhost:8383/mb-be/apis/getmaritimemessagelist.json');
$maritimes = $response->json['content'];
$cnt = count($maritimes);
for ($i=0; $i<$cnt; $i++) {
//var_dump($maritimes[$i]);
echo '<p class="brdr-bttm mrgn-lft-md ">';
echo $this->Html->link($maritimes[$i]['title'], array(
'controller' => 'messages',
'action' => 'view/'. $maritimes[$i]['id']
));
echo '<br />';
$date = $maritimes[$i]['created'];
echo $date;
echo '</p>';
}

I found a solution of this problem.
Here you can use DateTime::createFromFormat to format your created date. but it still has a problem with T inside the date '2016-05-16T17:21:10+0000', just because of timezone(I guess).
you can replace this T with space and got formatted created date as you want.
$http = new Client();
$response = $http->get('http://localhost:8383/mb-be/apis/getmaritimemessagelist.json');
$maritimes = $response->json['content'];
$cnt = count($maritimes);
for ($i=0; $i<$cnt; $i++) {
//var_dump($maritimes[$i]);
echo '<p class="brdr-bttm mrgn-lft-md ">';
echo $this->Html->link($maritimes[$i]['title'], array(
'controller' => 'messages',
'action' => 'view/'. $maritimes[$i]['id']
));
echo '<br />';
$date = $maritimes[$i]['created'];
//--------- Format created date --------
$string = str_replace("T"," ",$date);
$created_date = DateTime::createFromFormat('Y-m-d H:i:sO',$string)->format('Y-m-d');
echo $created_date;
echo '</p>';
}

Related

JQuery JEditable json select issue

I am working with JEditable but in json select I have an issue, because in the console show me the json but in the page the select input is empty.
Here the captures:
empty select
console showing the id
json result
Here the code:
require($_SERVER['DOCUMENT_ROOT'] . '/config.php');
$result = $conn->query("SELECT id_user_details, first_name, last_name
FROM users");
$return_arr = [];
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
$return_arr[] = array(
$row['id_user_details'] => $row['first_name'].' '.$row['last_name'],
);
};
$conn = null;
header('Content-type: application/json');
echo json_encode($return_arr);
Here the javascript:
$(".status").editable("include/users.php", {
type : "select",
loadurl : "include/select.php",
submit : "OK",
submitdata : {pk : $(this).attr('id'), _as_csrf_token: token},
indicator : '<img src="images/spinner.gif" />',
style : "inherit"
});
The where the select show if the client need to change the user
<td>
<a href="javascrip:void(0);" class="status" id="<?php echo $row['id_ch']; ?>" style="font-size:11px;">
<?php echo $row['doctor']; ?>
</a>
</td>
Well I finally did it!
I change the previously code:
require($_SERVER['DOCUMENT_ROOT'] . '/config.php');
$result = $conn->query("SELECT id_user_details, first_name, last_name
FROM users");
$return_arr = [];
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
$return_arr[] = array(
$row['id_user_details'] => $row['first_name'].' '.$row['last_name'],
);
};
$conn = null;
header('Content-type: application/json');
echo json_encode($return_arr);
To this one:
require($_SERVER['DOCUMENT_ROOT'] . '/config.php');
$result = $conn->query("SELECT id_user_details, first_name, last_name
FROM users");
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
$id_user_details = $row['id_user_details'];
$array[$id_user_details] = $row['first_name'].' '.$row['last_name'];
};
$conn = null;
header('Content-type: application/json');
print json_encode($array);

CSV Export from Wordpress | Sourcecode of page in file?

I'm trying to generate a csv-file from a database in wordpress.
The generated CSV-file contains the generated database array AND the HTML-sourcecode of the page.
Any idea what a solution could be to get rid of the HTML-Code?
The strategy with ob_start() / ob_end_clean(); seems not to work.
Thanks for your help.
<?php
ob_start();
$filename = 'provider.csv';
$headers = array('ID', 'Name', 'Location');
$handle = fopen('php://memory', 'w');
fputcsv($handle, $headers, ',', '"');
$results = $wpdb->get_results("SELECT * FROM provider");
foreach($results as $results1)
{
$row = array(
$results1->provider_id,
$results1->provider_name,
$results1->provider_location
);
fputcsv($handle, $row, ',', '"');
}
ob_end_clean();
fseek($handle, 0);
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename="' . $filename . '";');
fpassthru($handle);
fclose($handle);
?>
edited: This is how the csv-file looks like
edited: Screenshot of the solution from aniket patel
Please use below code I think it will work for you.
<?php
global $wpdb;
$filename = 'provider.csv';
$headers = array('ID', 'Name', 'Location');
$handle = fopen('php://output', 'w');
fputcsv($handle, $headers, ',', '"');
$results = $wpdb->get_results("SELECT * FROM provider");
foreach($results as $results1)
{
$row = array(
$results1->provider_id,
$results1->provider_name,
$results1->provider_location
);
fputcsv($handle, $row, ',', '"');
}
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename="' . $filename . '";');
exit;
?>

Display ratio as decimal between two PHP variables

I log stats for my Minecraft server and display player's in-game stats on my site. I log kills and deaths already, but now I'm trying to get a functioning kill/death ratio.
I am trying to display the kills/deaths in a decimal ratio format (Example: 3789 kills - 5711 deaths would give you a K/DR of 0.663)
elseif ($_GET['task'] == 'stats') {
$get_player = $_GET['player'];
$get_db = 'engine';
$result = mysql_query("SELECT * FROM $get_db WHERE name = '" . mysql_real_escape_string($get_player) . "'", $link);
while($data = mysql_fetch_array($result)) {
echo '{"task":"viewstats","kills":"'; echo $data['kills'];
echo '","deaths":"'; echo $data['deaths'];
echo '","joins":"'; echo $data['joins'];
echo '","quits":"'; echo $data['quits'];
echo '","kicked":"'; echo $data['kicked'];
echo '"}';
}
}
I call upon them in a table like this:
<td><?php echo empty($stats) ? "--" : substr($stats->kills, 0, 50); ?></td>
<td><?php echo empty($stats) ? "--" : substr($stats->deaths, 0, 50); ?></td>
The above PHP code is an API file and the MySQL is already enabled in it - I only posted a snippet of the API though.
You can do this:
echo json_encode(array(
'task' => 'viewstats',
'kills' => $data['kills'],
'deaths' => $data['deaths'],
'joins'=> $data['joins'],
'quits' => $data['quits'],
'kicked' => $data['kicked'],
// then ratio
'ratio' => $data['kills'] / $data['deaths'],
));
//**Make sure this Function is declared at the top of your script.**
function MySQLi_quickConnect()
{
$host = 'somewebsite.db.120327161.hostedresource.com'; //or 'http://localhost'
$username = '<YOUR USERNAME>';
$password = '<YOUR PASSWORD>';
$database = '<YOUR DATABASES NAME>';
$db = new MySQLi($host,$username,$password,$database);
$error_message = $db->connect_error;
if($error_message != NULL){die("Error:" . $error_message . "<br>" . "Occured in function
MySQLi_quickConnect");}
return $db;
}
//Replace your code with this:
elseif($_GET['task'] == 'stats') {
$get_player = $_GET['player'];
$get_db = 'engine';
$mysqli = MySQLi_quickConnect();
$query = ('SELECT kills, deaths, FROM ? WHERE name = ? ');
if ($stmt = $mysqli->prepare($query)) {
$stmt->bind_param("ss", $get_db, $get_player);
$stmt->execute();
$stmt->bind_result($kills, $deaths);
}
while ($stmt->fetch()) {
$kdr = $kills/$deaths;
echo "You have a K/DR of " . $kdr . "<br>";
}
$stmt->close();
}
Note: Verify your Database connection, table names, and $_Get variables.

quickbooks online interaction

I have a web app that I need to communicate with quickbooks online edition. I am able connect and receive data. The problem is is that the responce back that i get is not in a xml format or even better would be in json formate. How can I get it to respond back in one of those formats? Here is my code:
function request($xml, $certificate = null, $debug = false){
$ch = curl_init();
$header[] = 'Content-Type: application/x-qbxml';
$header[] = 'Content-Length: ' . strlen($xml);
$params = array();
$params[CURLOPT_HTTPHEADER] = $header;
$params[CURLOPT_POST] = true;
$params[CURLOPT_RETURNTRANSFER] = true;
$params[CURLOPT_URL] = $this->gateway;
$params[CURLOPT_TIMEOUT] = 30;
$params[CURLOPT_POSTFIELDS] = $xml;
$params[CURLOPT_VERBOSE] = $debug;
$params[CURLOPT_HEADER] = true;
// This is only for the HOSTED security model
if (file_exists($certificate))
{
$params[CURLOPT_SSL_VERIFYPEER] = false;
$params[CURLOPT_SSLCERT] = $certificate;
}
// Some Windows servers will fail with SSL errors unless we turn this off
$params[CURLOPT_SSL_VERIFYPEER] = false;
$params[CURLOPT_SSL_VERIFYHOST] = 0;
// Diagnostic information: https://merchantaccount.quickbooks.com/j/diag/http
// curl_setopt($ch, CURLOPT_INTERFACE, '<myipaddress>');
$ch = curl_init();
curl_setopt_array($ch, $params);
$response = curl_exec($ch);
if (curl_errno($ch))
{
$errnum = curl_errno($ch);
$errmsg = curl_error($ch);
_log('CURL error: ' . $errnum . ': ' . $errmsg, $debug);
return false;
}
// Close the connection
#curl_close($ch);
// Remove the HTTP headers from the response
$pos = strpos($response, "\r\n\r\n");
$response = ltrim(substr($response, $pos));
return $response;
}
function item_list(){
$xml =
'<?xml version="1.0"?>
<?qbxml version="6.0"?>
<QBXML>
<SignonMsgsRq>
<SignonTicketRq>
<ClientDateTime>' . date('Y-m-d') . 'T' . date('H:i:s') . '</ClientDateTime>
<SessionTicket>' . $this->session . '</SessionTicket>
<Language>English</Language>
<AppID>' . $this->application_id . '</AppID>
<AppVer>1</AppVer>
</SignonTicketRq>
</SignonMsgsRq>
<QBXMLMsgsRq onError="stopOnError">
<ItemQueryRq>
<OwnerID>0</OwnerID>
</ItemQueryRq>
</QBXMLMsgsRq>
</QBXML>';
$response = $this->request($xml, null, true);
echo $response;
}
Thanks
Here my xml request:
$xml =
'
' . date('Y-m-d') . 'T' . date('H:i:s') . '
' . $this->session . '
English
' . $this->application_id . '
1
0
</QBXMLMsgsRq>
</QBXML>';
Here is my responce:
2013-04-12T12:28:11 V1-115-Q03kydq32h22tnfqnd5izf:689712285 1 2013-04-10T06:02:40 2013-04-10T06:02:40 0 Sales Sales 0 0 1 Sales 2 2013-04-10T21:20:43 2013-04-10T21:20:43 0 test product test product 0 0 1 Sales
My stupid mistake. I was echoing my result to browser which interpreted xml tags as html tags. I used $xml = simplexml_load_string($response); print_r($xml); to view response in browser.

Google API for analytics invalid grant but works sometimes

I've been on this problem now for 2 days and have tried looking under google code and stackoverflow but still can come up with an answer.
My problem is when I try my google analytics api I get "Error refreshing the OAuth2 token, message: '{ "error" : "invalid_grant" }'"
But the weird part is that some times it will work. rarely but if I refresh and keep trying it, it will output.
The only thing I could find is that it could be the refresh token limit has been exceeded
Attached is my code if someone could help me out or point me to the right direction.
Thanks!
<?php
session_start();
require_once 'Google_Client.php';
require_once 'Google_AnalyticsService.php';
require_once 'config.php';
$keyFile = 'key.p12';
$client = new Google_Client();
$client->setApplicationName("test");
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
$client->setAssertionCredentials(new Google_AssertionCredentials(
GOOGLE_SERVICE_ACCOUNT,
array('https://www.googleapis.com/auth/analytics.readonly'),
file_get_contents($keyFile))
);
$client->setClientId(GOOGLE_CLIENT_ID);
$client->setAccessType('offline');
$client->setUseObjects(true);
$service = new Google_AnalyticsService($client);
try {
$results = $service->data_ga->get(
'ga:44444444',
date('Y-m-d', strtotime('-30 days '.date('Y-m-d', strtotime('-1 day '.date('Y-m- d'))))),
date('Y-m-d', strtotime('-1 day '.date('Y-m-d'))),
'ga:visits,ga:newVisits',
/*array(
'dimensions' => 'ga:source,ga:keyword',
'sort' => '-ga:visits,ga:keyword',
'filters' => 'ga:medium==organic',
'max-results' => '25'
)*/
array('dimensions' => 'ga:date')
);
} catch (Google_ServiceException $e) {
// echo $e->getMessage();
}
if ($client->getAccessToken()) {
$_SESSION['token'] = $client->getAccessToken();
}
$dateParsePattern = '/"Date.parse\(\\\"((\d{4})-(\d{2})-(\d{2})) UTC\\\"\)"/';
$dateParseReplacement = 'Date.parse("$1 UTC")';
$allVisitsItems = array();
$newVisitorsItems = array();
if ($results && count($results->getRows()) > 0) {
foreach ($results->getRows() as $row) {
$date = 'Date.parse("'.date("Y-m-d", strtotime($row[0])).' UTC")';
$allVisitsItems[] = array($date, intval(htmlspecialchars($row[1], ENT_NOQUOTES)));
$newVisitorsItems[] = array($date, intval(htmlspecialchars($row[2], ENT_NOQUOTES)));
}
}
header('Content-Type: application/json');
?>
<?php echo preg_replace($dateParsePattern, $dateParseReplacement, json_encode($allVisitsItems)) ?>
Edit - It's not the NTP, when I echoed date('l jS \of F Y h:i:s A'); it matched up.
The following works to generate output - make sure you are running PHP 5.3 or higher.
<?php
require_once './src/Google_Client.php';
require_once './src/contrib/Google_AnalyticsService.php';
$path_to_keyfile = '.p12';
$service_account_email = '7#developer.gserviceaccount.com';
$client_id = '7.apps.googleusercontent.com';
$analytics_profile_id = 'ga:IN URL OF ANALYTICS';
$client = new Google_Client();
$client->setApplicationName("API TEST");
$client->setAssertionCredentials(
new Google_AssertionCredentials(
$service_account_email,
array('https://www.googleapis.com/auth/analytics.readonly'),
file_get_contents($path_to_keyfile)
)
);
$client->setClientId($client_id);
$client->setAccessType('offline_access');
$service = new Google_AnalyticsService($client);
$from = date('Y-m-d', strtotime('-30 days '.date('Y-m-d', strtotime('-1 day '.date('Y-m-d'))))); // 30 days
$to = date('Y-m-d', strtotime('-1 day '.date('Y-m-d'))); // yesterday
$dateParsePattern = '/"Date.parse\(\\\"((\d{4})-(\d{2})-(\d{2})) UTC\\\"\)"/';
$dateParseReplacement = 'Date.parse("$1 UTC")';
$allVisitsItems = array();
$newVisitorsItems = array();
try {
$data = $service->data_ga->get(
//
$analytics_profile_id,
$from,
$to,
'ga:visits,ga:newVisits',
array('dimensions' => 'ga:date')
);
if($data && $data['totalResults'] > 0) {
foreach($data['rows'] as $row) {
$date = 'Date.parse("'.date("Y-m-d", strtotime($row[0])).' UTC")';
$allVisitsItems[] = array($date, intval(htmlspecialchars($row[1], ENT_NOQUOTES)));
$newVisitorsItems[] = array($date, intval(htmlspecialchars($row[2], ENT_NOQUOTES)));
}
}
header('Content-Type: application/json');
?>
<?php echo preg_replace($dateParsePattern, $dateParseReplacement, json_encode($allVisitsItems)) ?>
<?php echo preg_replace($dateParsePattern, $dateParseReplacement, json_encode($newVisitorsItems)) ?>
<?php
} catch(Exception $e) {
echo 'There was an error : - ' . $e->getMessage();
}