no-one no-one - 5 months ago 14
JSON Question

How to cut off characters in JSON element

I have following PHP code:



$curl = curl_init();

curl_setopt_array($curl, array(
CURLOPT_URL => "SOME_URL",

CURLOPT_RETURNTRANSFER => true,
CURLOPT_VERBOSE => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache",
"postman-token: 32bee9e5-7618-3b97-0239-f9f0185c7396"
),
));

$response = curl_exec($curl);

$err = curl_error($curl);

curl_close($curl);

$response = json_decode($response, true);

$reversed = array_reverse($response);

foreach($reversed as $json){
echo '<p>' . '<strong>' . $json['date'] . ' by ' . $json["display_name"] . '</strong>' . '</p>' . '</ br>' . '<p>' . $json["description"] . '</p>';
}

if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}



?></code>


When I do the echo from my reversed loop I get e.g. following output on DATE element:
2016-03-01 08:03:00.0

I would like to remove always last characters which are ":00.0".

I have tried with many php functions, but I am failing with this.

Answer

Use strtotime and date functions to get the needed format:

// let's say $json['date'] contains "2016-03-01 08:03:00.0"
echo date("Y-m-d H:i", strtotime($json['date']));  // will output "2016-03-01 08:03"
Comments