I am trying to use PhpPresentation to dinamically generate PowerPoint presentations with charts in PHP, using Google Analytics as data source.
I can make both processes independently (1. generating the pptx using a manually defined array of data and 2. generate an array in JavaScript with data from Google Analytics Core Reporting API). However, I am not able to combine both processes sucessfully (pass JavaScript's array and use it in PHP instead of my manually defined array).
1. generating the pptx using a manually defined array in php
If I use the following array as data source (as defined in PhpPresentation documentation), the PowerPoint is generated without problem:
$series2Data = array('20151201' => 266.1, '20151202' => 198.5, '20151203' => 271.8);
2. generate an array with data from Google Analytics Core Reporting API
The stringified array generated with JavaScript is:
[{"date":"20151201","avgSessionDuration":266.1},{"date":"20151202","avgSessionDuration":198.5},{"date":"20151203","avgSessionDuration":271.8}]
I am passing this array to the php that generates my PowerPoint:
<form method="post" id="theform" action="Sample_05_Chart.php">
<input type="hidden" id="markers" name="markers">
<button>Submit</button>
</form>
<script>
window.onload = function() {
var form = document.getElementById('theform');
form.addEventListener('submit', function(){
var markersField = document.getElementById('markers');
var markers = data2;
markersField.value = JSON.stringify(markers);
});
}
</script>
And in the PHP file I have added:
$markers = json_decode($_POST['markers']);
$series2Data = $markers;
However, the generated PowerPoint is corrupted, as I believe the array structure isn't what PhpPresentation expects.
My array's knowledge, however, is not so good in PHP as it is in JavaScript.
How could I transform an array, whose var_dump looks like
array(3) { [0]=> object(stdClass)#4 (2) { ["date"]=> string(8) "20151201" ["avgSessionDuration"]=> float(266.1) } [1]=> object(stdClass)#9 (2) { ["date"]=> string(8) "20151202" ["avgSessionDuration"]=> float(198.5) } [2]=> object(stdClass)#10 (2) { ["date"]=> string(8) "20151203" ["avgSessionDuration"]=> float(271.8) } }
into an array as described in point 1?
First of all, json_decode takes an optional second argument. First, the json string you wish to decode and second a boolean value which tells it whether or not to decode as an array of objects (stdClass) or as an associative array.
If you want the an associative array of the data posted, just use json_decode($markers, true).
However, the format you are asking for will not be given by this. So you need to massage the data some either in javascript or php.
Here's the php code to transform it:
$series2Data = [];
$markers = json_decode($_POST['markers'], true);
foreach ($markers as $marker) {
$series2Data[$marker['date']] = $marker['avgSessionDuration'];
}
Javascript:
function formatMarkersToData(markers) {
var series2Data = {};
for (var i = 0; i < markers.length; i++) {
var marker = markers[i];
series2Data[marker.date] = marker.avgSessionDuration;
}
return series2Data;
}
markersField.value = JSON.stringify(
formatMarkersToData(markers)
);
What both of these blocks of code do is loop over your data and set the index and value according to the required format of date => avgSessionDuration in the series2data variable. The javascript uses an object to allow for manually setting the key.
The above javascript code would then allow you to just use json_decode($_POST['markers'], true); to get the proper associative array for your $series2Data. Otherwise, you'll need the PHP code to do the massaging before passing it off to PhpPresentation.
It just depends on at what point you want the data transformed - on the server, or on the client. If this is at all confusing, please let me know.
Related
This question already has answers here:
Serializing PHP object to JSON
(11 answers)
Closed 4 years ago.
The array below could return in various ways (with more or less elements):
array(4) { ["imagen"]=> string(11) "bánner.jpg" ["alt"]=> string(5) "muaka" ["destino"]=> string(7) "op_tipo" ["tipo"]=> string(13) "obj_connected" }
array(3) { ["imagen"]=> string(12) "Logo_RGB.jpg" ["alt"]=> string(7) "test123" ["destino"]=> string(11) "op_list_gen" }
Im saving this in a variable in PHP called: $filtrosBanner;. How can I get the values from this in jQuery?
I have saved the variable in jQuery as follows:
var opDestino = "<?php echo $filtrosBanner; ?>";
This returns an array but im not sure how to access each value individually.
The most simple approach for your task would be:
var opDestino = <?php echo json_encode($filtrosBanner); ?>;
This way you are converting an object (or array) from PHP to Javascript syntax.
I would use json_encode(). This should create a json object for your var opDestino.
Like so:
var opDestino = <?php echo json_encode($filtrosBanner); ?>;
You need to implode your array as string using your PHP code and save it in a php variable as
PHP
$myarray=implode(',',$array);
Now take it in a variable in your script and then explode it using , to get your final array as
JQUERY
var myarray='<?php echo $myarray;?>';
var originalarray=myarray.split(',');
Note: but it will work for only indexed array, not associative array
Return the array with json_encode in PHP.
return json_encode($filtrosBanner);
In Javascript/jQuery use
var obj = JSON.parse(<?php echo $filtrosBanner?>);
To use this object , use it like this.
obj.propertyname
I have an array stored in php: $cv1 = array('a','b');
As you can see in the code below, I am trying to get the respective data from the array then delegate it to two separate functions.
But the data returned from the php callback function is: 'Array' instead of 'a','b';
and result[0] gets 'A' result[1] gets 'r' etc.
Thanks for help!
js:
$('a').on('click',function(){
var cv = $(this).data('cv');
var url= '_php/myphp.php';
$.post(url,{contentVar:cv},function(data) {
result=data;
return result;
}).done(function() {
alert(result[0]);
$('#myDiv').html(result[1]);
});
});
php:
$cv1 = array("a","b");
$contentVar = $_POST['contentVar'];
if($contentVar == "cv1")
{
echo json_encode($cv1);
}
It's common in PHP for you to get "Array" instead of an actual array when it accidentally gets cast to a string. That's not what you're doing here though; we can test:
> $cv1 = array("a","b");
array(2) {
[0] =>
string(1) "a"
[1] =>
string(1) "b"
}
> json_encode($cv1);
string(9) "["a","b"]"
$cv1 gets encoded correctly.
You must be treating it like a string somewhere else:
> (string)array("a","b")
! Array to string conversion
string(5) "Array"
Also, why do you have two success callbacks in $.post? The 3rd argument is a success callback, which works the same as .done. Use one or the other (I recommend done) but not both.
You may also consider passing json as the last argument (dataType) so that jQuery knows what to expect and will properly decode the result.
Try to do something like this:
$.post(url,{contentVar:cv}
function(response)
{
alert(response[0]);
},'json'
);
You need to convert the json string format to a javascript object/array.
var result = $.parseJSON(data);
see this question jQuery ajax request with json response, how to? for more detail.
But there is something strange that, if is returning 'Array', the php is not converting the array to json, what happens if the ($contentVar == "cv1") return false? If you will return an array to javascript you need to convert to a string (and the json format is perfect for this).
In my php file im using the following,
$obj = ($_POST['data']);
var_dump(json_decode($obj,true));
And i see this result. Is this the correct format? and how do i access the array.
eg, set a new variable $newID the same as row1 id
array(4) {
["row0"]=>
string(92) "{"id":"157","name":"123","basic":"123123123","submitter":"Keith","status":"review"}"
["row1"]=>
string(169) "{"id":"158","name":"TEST RESOURCE","basic":"Please state the type of work.","submitter":"Keith","status":"review"}"
["row2"]=>
string(107) "{"id":"159","name":"TEST OTHER","basic":"testing for other","submitter":"Keith","status":"review"}"
["row3"]=>
string(160) "{"id":"160","name":"Name","basic":"type of work","submitter":"Keith","status":"review"}"
}
heres whats in POST in firebug
data {"row0":"{\"id\":\"157\",\"name\":\"123\",\"basic\":\"123123123\",\"submitter\":\"Keith\",\"status\":\"review\"}","row1":"{\"id\":\"158\",\"name\":\"TEST RESOURCE\",\"basic\":\"Please state the type of work.\",\"submitter\":\"Keith\",\"status\":\"review\"}","row2":"{\"id\":\"159\",\"name\":\"TEST OTHER\",\"basic\":\"testing for other\",\"submitter\":\"Keith\",\"status\":\"review\"}","row3":"{\"id\":\"160\",\"name\":\"Name\",\"basic\":\"type of work\",\"submitter\":\"Keith\",\"status\":\"review\"}"}
Each "row" of the array is another JSON string. It seems like the data was double-encoded, like:
$array = json_encode(
array(
'row0' => json_encode(array('id' => '157', ...)),
...
)
)
This is incorrectly encoded data, unless you wanted JSON objects inside JSON objects. To work with it, you need to json_decode each individual item again. Better though: fix the encoding step.
I am sending an array in php (converted from a string using explode), to a seperate javascript page. I was wondering how do I get into the javascript array and actually retrieve data values.
array in javascript (from php file)-
array(2) {
[0]=>
string(2) "30"
[1]=>
string(0) ""
}
array(2) {
[0]=>
string(2) "30"
[1]=>
string(0) ""
}
Here is the ajax call on the javascript page -
$.ajax({
url: "GetTest.php",
type: "POST",
success: function(data){
alert("success");
console.log(data);
},
error: function(data){
alert('failure');
}
});
on the php page -
var_dump((explode(',', $something));
How do I get in here and pull out the "30" value. I am using an ajax call to get this data, and then putting placing this array in a variable called "data", but if I do something like data[0], I get the letter "a" as a response.
Any help towards this will be greatly appreciated.
Thanks,
If you are returning the array itself, it will not be converted to a JavaScript object. I believe you will just get the string "Array". What you need to do is call json_encode($your_array) to convert the array to a JavaScript object. Then, PHP will return a JavaScript object that looks like this:
{
"0": "30",
"1": ""
}
You can then call JSON.parse on the response and access the data in that object as you would any other JavaScript object.
Note: If you are using PHP < 5.2 and do not have the JSON PECL extension installed, the json_encode() function will not be available, and you will need to either write a function to convert an array to JSON or find one that someone else has written.
A JavaScript array should look like this...
var myArray = ["30", "0"];
You probably have a string instead of an array if you get an 'a' at index 0.
"array"[0] === "a"
So you need to fix your client side array first.
In pure javascript:
xhr.onreadystatechange = function()//where xhr is your request object
{
if (this.readyState === 4 && this.status === 200)
{
var yourArray = JSON.parse(this.responseText);
console.log(yourArray);//logs the array above, normally
}
};
Be aware that IE, prior to 9 at least, does not come with JSON support as standard, in which case, just google JSON.js and include it in the header. Also make sure that the array you send is json_encode'ed before you echo it.
Looking at the code you added, I'd say: replace the var_dump by echo json_encode(explode(',',$someString)); and you're all set
I have a php-function to fetch events as objects and I want to add them to my existing ul-list via JQuery. I want to transfer the php-variable to JQuery and want to iterate this variable to build up the HTML. I tried it with this one:
$pastEvents = event::getPastEvents($team);
var test = { pastEvents : '<?php echo $pastEvents; ?>' };
for (obj in test.pastEvents) {
console.log(obj);
}
The result i get is only 0, 1, 2, 3, 4, 5,... in the console. The var_dump from PHP looks like this:
array(8) { [0]=> object(game)#10 (17) { ["creatorid":protected]=> int(1) ["tid":protected]=> int(1) ["eid":protected]=> int(12) ["art":protected]=> int(1) ["spielart":protected]=> int(1) ["zeitpunkt":protected]=> string(19) "2012-02-28 11:20:00" ["zeit":protected]=> string(19) "2012-02-18 11:21:50"
How can i access the objects from PHP? How can i iterate the variable correctly, that i can access the data like obj.creatorid ... ?
Thanks!
P.S: I could solve this by using jquery's ajax-function - but before the user clicks i already have the data available - so the ajax-request is needless.
You need to use php method json_encode() to convert to json.
echo json_encode( $array);
Then in jQuery ( using ajax)
$.getJSON( url, function(data){
console.log( data)// log the whole json object to console
})
You need to use JSON. Look up the JSON and the PHP functions json_encode and json_decode.
Use JSON possibilites. Convert your php data to JSON. That can be easily understood from Javascript.
json_encode($myData);
json_decode($myData);
To read, JSON, in Javascript, simply access it as an object.
myObject.myField