I'm trying to retrieve tasks from Rembmer the Milk API. I run this code:
$array = json_decode($content, true);
foreach($array['rsp']['tasks']['list']['taskseries'] as $keys=>$val) {
$task = $val['name'];
$duedate = $val['task']['due'];
echo $task." ";
echo $duedate."<br>";
}
but I am getting this error:
Fatal error: Cannot use string offset as an array in C:** on line 66
(line 66 being $duedate = $val['task']['due'];)
This is the JSON response I am trying to decode (trying to get "name":"SOMETHING" and "due":"2011-03-17T04:00:00Z":
{"rsp":{"stat":"ok","tasks":{"rev":"[CODE]","list":{"id":"[ID NUMBER]","taskseries": {"id":"ID","created":"DATE CREATED","modified":"DATE","name":"SOMETHING","source":"js","url":"","location_id":"","tags":[],"participants":[],"notes":[],"task":{"id":"ID","due":"2011-03-17T04:00:00Z","has_due_time":"0","added":"DATE","completed":"","deleted":"","priority":"1","postponed":"0","estimate":""}}}}}}
How to fix?
Thanks!!!!!
UPDATE
This is the JSON response for two or more tasks:
{"rsp":{"stat":"ok","tasks":{"rev":"NUMBER","list":{"id":"ID NUMBER","taskseries":[{"id":"ID NUMBER","created":"CREATED DATE","modified":"DATE","name":"TASK 3","source":"js","url":"","location_id":"","tags":[],"participants":[],"notes":[],"task":{"id":"ID","due":"2011-03-18T04:00:00Z","has_due_time":"0","added":"DATE","completed":"","deleted":"","priority":"1","postponed":"0","estimate":""}},{"id":"ID","created":"DATE","modified":"DATE","name":"SOMETHING","source":"js","url":"","location_id":"","tags":[],"participants":[],"notes":[],"task":{"id":"ID","due":"2011-03-17T04:00:00Z","has_due_time":"0","added":"DATE","completed":"","deleted":"","priority":"1","postponed":"0","estimate":""}}]}}}}
Try this:
$taskSeries=$array['rsp']['tasks']['list']['taskseries'];
if(array_key_exists('id', $taskSeries)) {
$taskSeries=array($taskSeries);
}
foreach($taskSeries as $task) {
$name=$task['name'];
$due=$task['task']['due'];
// do something with $name and $due here
}
Related
Currently, I created a system that uses daypilot calendar. For example, when I clicked a date, it will show the list of activities on that selected date.
Below code is successful display the list:
<?php
require_once '../../../config/configPDO.php';
$Fac_ID = strtolower($_GET['Fac_ID']);
$Room_Desc = strtolower($_GET['Room_Desc']);
$stmt = $conn->prepare("SELECT * FROM booking LEFT JOIN room ON booking.Room_ID = room.Room_ID
WHERE room.Fac_ID = '$Fac_ID' AND room.Room_Desc = '$Room_Desc' AND Book_Status <> 'Reject'");
$stmt->execute();
$result = $stmt->fetchAll();
class Event {}
$events = array();
foreach($result as $row) {
$e = new Event();
$e->id = $row['Book_No'];
$e->text = "Meeting Name: ". $row['Meeting_Description']. " || " ."Requested by: ".$row['Requested_by']. " || " ."Location: ".$row['Fac_ID']. ", " .$row['Room_Desc'];
$e->start = $row['StartTime'];
$e->end = $row['EndTime'];
$events[] = $e;
}
header('Content-Type: application/json');
echo json_encode($events);
?>
But, when I change the code (Because want to retrieve json data), the data doesn't display at calendar.
Below is the code:
<?php
require_once '../../../config/configPDO.php';
$Fac_ID = strtolower($_GET['Fac_ID']);
$Room_Desc = strtolower($_GET['Room_Desc']);
//retrieve json
$url = "http://172.20.0.45/TGWebService/TGWebService.asmx/displayPABooking?Fac_ID=$Fac_ID&Room_Desc=$Room_Desc&Room_ID=&Book_No=&Book_Date_From=&Book_Date_To=";
$data = file_get_contents($url); //line 10
$json = json_decode($data);
$result = $json->bookingList; //line 12
class Event {}
$events = array(); //
foreach($result as $row) { //line 17
$e = new Event();
$e->id = $row->bookNo;
$e->text = "Meeting Name: ".$row->desc. " || " ."Requested by: ".$row->requestedBy." || " ."Location: ".$row->facID.", " .$row->roomName;
$e->start = $row->startTime;
$e->end = $row->endTime;
$events[] = $e;
}
header('Content-Type: application/json');
echo json_encode($events);
?>
And, This is the error that I found at console:
PHP Warning: file_get_contents(http://172.20.0.45/TGWebService/TGWebService.asmx/displayPABooking?Fac_ID=TGT&Room_Desc=LEVEL 1 &Room_ID=&Book_No=&Book_Date_From=&Book_Date_To=): failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request
in C:\inetpub\wwwroot\ebooking\pages\manual_booking\backend\backend_events.php on line 10
PHP Notice: Trying to get property 'bookingList' of non-object in C:\inetpub\wwwroot\ebooking\pages\manual_booking\backend\backend_events.php on line 12
PHP Warning: Invalid argument supplied for foreach() in C:\inetpub\wwwroot\ebooking\pages\manual_booking\backend\backend_events.php on line 17
Can I know where I need to change? Thanks
This is probably because of the space in "Level 1". Try urlencoding your $_GET parameters:
$url = "http://172.20.0.45/TGWebService/TGWebService.asmx/displayPABooking?Fac_ID=" . urlencode($Fac_ID) . "&Room_Desc=" . urlencode($Room_Desc) . "&Room_ID=&Book_No=&Book_Date_From=&Book_Date_To=";
If you want to make the variable substitution more explicit, you could use strtr:
$template = "http://172.20.0.45/TGWebService/TGWebService.asmx/displayPABooking?Fac_ID={Fac_ID}&Room_Desc={Room_Desc}&Room_ID=&Book_No=&Book_Date_From=&Book_Date_To=";
$url = strtr($template, array(
'{Fac_ID}' => $Fac_ID,
'{Room_Desc}' => $Room_Desc
));
I am trying to remove a tab character from a json_encoded data from php? Every time I try to fetch data from the script as JSON enocded format I use the following code below to parse my data but can not get the jsonStr to be parsed.
The error I am getting is
Error: JSON.parse: unexpected character at line 1 column 1 of the JSON
data
Code
jsonStr = data.toString();
jsonStr = JSON.stringify(jsonStr.replace("\t",""));
totJSON = JSON.parse(jsonStr['totalActionItems']);
How do I resolve this error to parse a well formed json string correctly?
EDIT
Corrected Parsing Code (JS)
$.ajax({url: "/dashboard/chartdata.php?chart=buildup", success: function(data)
{
jsonStr = data.replace(/\t/g, "");
console.log(jsonStr);
json = JSON.parse(jsonStr);
totJSON = json['totalActionItems'];
PHP Code
function getData($field, $rows)
{
$minDate = $rows[0][$field];
$maxDate = $rows[count($rows)-1][$field];
$date = $minDate;
$findDate = $minDate;
$idx = 0;
$tot = 0;
$dates = array();
$numActionItems = array();
while ($date < $maxDate)
{
if ($rows[$idx][$field] == $date)
{
$tot += $rows[$idx]['numactionitems'];
$idx++;
}
$timestamp = strtotime($date);
$date = date('Y-m-d', strtotime($date . "+1 days"));
$numActionItems[] = array('x'=>$timestamp*1000, 'y'=>$tot);
}
return $numActionItems;
}
function getBuildUpData($field)
{
$manageCharts = new manageCharts();
$rows = $manageCharts->buildup($field);
$items = getData($field, $rows);
return $items;
}
if (isset($_GET['chart']) && $_GET['chart'] == 'buildup')
{
$json = json_encode(['totalActionItems' => getBuildUpData('assigneddate'),
'ecdItems' => getBuildUpData('ecd'),
'originalDueItems' => getbuildUpData('duedate'),
'closedItems' => getBuildUpData('closeddate')]);
echo $json;
}
The following code helped produce the correct json for processing.
jsonStr = data.replace(/\t/g, "");
//console.log(jsonStr);
json = JSON.parse(jsonStr);
totJSON = json['totalActionItems'];
Help me, i wanna put the timestone to this format Hour:minutes:secondes
$services = $pdo ->prepare("SELECT * FROM `servicos` WHERE `DE` = :u");
$services->bindValue(":u", "1");
$services->execute();
echo $numServico = $services->rowCount(); // Contagem de serviços
$l = $services->fetchAll(PDO::FETCH_OBJ);
//$json = json_encode($l);
echo '{"data":[';
//echo $json;
foreach ($l as $listar) {
$inicioHora = new DateTime("listar->REGISTRO");
$inicioHora = $inicioHora->format('H:i:s');
}
But i receive this
Fatal error: Uncaught exception 'Exception' with message 'DateTime::__construct(): Failed to parse time string (listar->REGISTRO) at position 0 (l): The timezone could not be found in the database' on line 26
if the field $listar->REGISTRO is a timestamp, then you only need to use the date() function http://php.net/manual/en/function.date.php
$time = date('H:i:s', $listar->REGISTRO);
Replace this:
$inicioHora = new DateTime("listar->REGISTRO");
$inicioHora = $inicioHora->format('H:i:s');
With this:
$inicioHora = date('H:i:s', strtotime($listar->REGISTRO));
we are using PostGreSql database, when we run following code unit, it shows error of.
Severity: Warning
Message: Illegal string offset 'server'
Filename: postgre/postgre_driver.php
Message: Cannot modify header information - headers already sent by (output started at system/core/Exceptions.php:185)
Model Code:
public function tracks_add( $id ) {
$cnt = 0;
$date = date('Y-m-d H:i:s');
$s_title = $this->input->post('s_title');
$s_singer = $this->input->post('s_singer');
$s_url = $this->input->post('s_url');
foreach ($s_title as $s_title) {
$this->db->set( array('a_id'=> $id, 's_title' => $s_title, 's_singer' => $s_singer[$cnt], 's_url' => $s_url[$cnt], 'date'=> $date) );
$this->db->insert('soundtracks');
$cnt++;
}
}
You can find this issue here :
Postgres db driver insert issue
Change line 331 to
$v = pg_version($this->conn_id); $v = isset($v['server']) ? $v['server'] : 0; // 'server' key
Have this sample.xml:
<FacturacionAR>
<Factura xsi:type="FacturaAR">
<TipoNota>Boleta de Ventas y Servicios</TipoNota>
<Agencia>LUIL</Agencia>
<NroFactura>5040</NroFactura>
<Cliente>JOHAO SMITH CART</Cliente>
<Ciudad>NUNORK</Ciudad>
<Direccion>CALLE VITAL DE MELLO</Direccion>
<Barrio>JAJJKIU</Barrio>
<Estado>Cancelada</Estado>
</Factura>
</FacturacionAR>
I want to add "Telefono" every time this node is missing, just after "Barrio", so I tried to do in php:
$filename = "sample.xml";
$FacturacionAR = simplexml_load_file($filename,null,true);
function simplexml_insert_after(SimpleXMLElement $sxe, SimpleXMLElement $insert, SimpleXMLElement $target)
{
$target_dom = dom_import_simplexml($target);
$target_dom->formatOutput = true;
$target_dom->preserveWhiteSpace = false;
$insert_dom = $target_dom->ownerDocument->importNode(dom_import_simplexml($insert), true);
if ($target_dom->nextSibling) {
$result = $target_dom->parentNode->insertBefore($insert_dom, $target_dom->nextSibling);
$target_dom->parentNode->insertBefore($target_dom->ownerDocument->createTextNode("\n"), $result);
return $result;
} else {
return $target_dom->parentNode->appendChild($insert_dom);
}
}
foreach ($FacturacionAR->Factura as $Factura) {
if (!isset($Factura->Telefono)) {
$meta2 = new SimpleXMLElement("<Telefono/>");
$target = current($FacturacionAR->xpath('//Barrio[last()]'));
simplexml_insert_after($FacturacionLocalizaAR, $meta2, $target);
}
}
The expected result is:
<Barrio>JAJJKIU</Barrio>
<Telefono></Telefono>
But when I run the php script, this error appears:
PHP Catchable fatal error: Argument 3 passed to simplexml_insert_after() must be an instance of SimpleXMLElement, boolean given
Any ideas?
OK. Upgrading to PHP 5.5.3 solved my problem.