Create and edit file javascript with "file_put_contents"? - javascript

i would like to create a file.js with php but i think that in my code there are a lot of errors:
i have multidimensional array:
$report= array();
$report= array(array(3,6),array(4,8));
that is:
Array
(
[0] => Array
(
[0] => 3
[1] => 6
)
[1] => Array
(
[0] => 4
[1] => 8
)
)
Set a content-type for js file
$header = "Content-type: text/javascript";
$dir = "outreport/";
$nomefile = "report.js";
//delete a file with same name if exists
foreach (glob($dir."*".$nomefile) as $v){
unlink($v);
}
$percorso = $dir.$nomefile;
file_put_contents($percorso, $report);
header($header);
print($report);
There are two problems:
1) when launching the file.php asks me to download the same file but in javascript
2) in the "outvulcani" it creates the file report.js but is empty
I wish that in the file "report.js" there is the array $report but
written in javascript code:
var reports = [
[3,6]
[4,8]
];
Kindly, you can help me out?
Thanks a lot!
Sorry for my english

PHP has an function to convert Arrays to JSON. You could use this code for "inspiration".
$report = array(array(3,6),array(4,8));
$javascriptContent = json_encode($report);
// Convert to string
$javascriptContent = "var reports = ". $javascriptContent . ";\n";
file_put_contents($percorso, $javascriptContent);
The reason for "Download" is the header, please remove it.

Related

Save data to JSON File in correct format - PHP

I am currently saving click co-ordinates to a JSON file through the use of the following code:
onmouseup = function(e){
var Clicks = {};
Clicks.state = {
cX: e.clientX,
cY: e.clientY,
}
$.ajax({
type : "GET",
url : "PHP/save_json.php",
data : {
state : JSON.stringify(Clicks.state)
}
});
}
<?php
$myFile = "JSON/clicks.json";
$fh = fopen($myFile, 'a') or die("can't open file");
$stringData = $_GET["state"];
fwrite($fh, $stringData);
fclose($fh)
?>
However with the above code I am saving the coordinates in the following incorrect format:
{"cX":467,"cY":374}{"cX":56,"cY":474}
Can anyone please help me to save the coordinates in a JSON array rather than in seperate JSON entries?
I would like the file to be as follows, were the coordinates are added onto the already existing JSON array within the file:
{
"ID":["1","2"],
"cX":["467","56"],
"cY":["374","474"]
}
What you need to do is:
Open the clicks.json file and read the entire contents.
Turn this into an instance of stdClass by using json_decode. This will give you a PHP object that you can modify using normal PHP functions and syntax.
Use json_decode on the JSON that you receive from your client.
Use array_push to push the new values from the client into the arrays stored in the file (something like array_push($fileJson->cX, $clientJson->cX);)
Use json_encode to encode $fileJson again.
Write it back to the file.
This assumes that the clicks.json file is already correctly formatted JSON with the arrays already created etc.
Given the current arrangement of the key and value bits, it's apparent that some sort of transformation is needed in the JSON data before it is written to the file. Where this transformation is done is definitely a matter of an opinion. However, assuming that you receive following JSON data in PHP:
[{"cX":467,"cY":374},{"cX":56,"cY":474}]
The PHP code can be written as (illustrated with static input):
$myFile = "JSON/clicks.json";
$fh = fopen($myFile, 'a') or die("can't open file");
$stringData = $_GET["state"];
$json_array_source = json_decode($string, true);
$json_array_target = array();
foreach($json_array_source as $key=>$value){
$json_array_target["ID"][] = $key + 1;
foreach($value as $sub_key => $sub_value){
$json_array_target[$sub_key][] = $sub_value;
}
}
$transformed_string = json_encode($json_array_target);
fwrite($fh, $transformed_string);
fclose($fh);
If you were to echo $transformed_string;, you'd see:
{"ID":[1,2],"cX":[467,56],"cY":[374,474]}
Which is what will be written to the file.
You need load data to array, add new data and save back to file.
I think you don't need save numbers in strings.
These code create new file if not exists.
<?php
// test input data
if(isset($_GET['state']['cX']) &&
isset($_GET['state']['cY']) &&
is_numeric($_GET['state']['cX']) &&
is_numeric($_GET['state']['cY']) )
{
// ok
} else {
exit('Bad data format');
}
$myFile = __DIR__ . "/JSON/clicks.json";
// step 1, load data from file to array
$array = file_exists($myFile) ?
json_decode(file_get_contents($myFile), true) :
[];
// step 2, add data to array
$array['ID'][] = isset($array['ID']) ? (count($array['ID']) + 1) : 1;
$array['cX'][] = (int) $state['cX'];
$array['cY'][] = (int) $state['cY'];
// step 3, save array back to file
file_put_contents($myFile, json_encode($array));
Or you can use other file format where will be possible to append file. The easiest format for static structured data could be CSV
Use json_encode to convert your string to an object, then convert it back to a string using json_decode and the JSON_PRETTY_PRINT option.
$stringData = json_decode(json_encode($_GET["state"]), JSON_PRETTY_PRINT);
http://php.net/manual/en/function.json-encode.php

JSON passes string instead of array or object from PHP to Javascript

I am having som trouble with passing a multidimensional and associative array from php to Javascript. I converte it with JSON, using:
_SESSION = '<?php print json_encode($_SESSION) ?>';
I have also tried
_SESSION = '<?php print json_encode($_SESSION, JSON_PRETTY_PRINT) ?>';
_SESSION = $.parseJSON('<?php print json_encode($_SESSION) ?>');
both of them give me errors like: Uncaught SyntaxError: Unexpected token ILLEGAL.
However, the first one doesn't give me any errors and I can access it in Javascript. It then outputs:
{"items":{"221163":{"CodeComplete":null,"Project":"Coding","Team":"Mail","TimeSpent":25","Children":[]}}, {"221165":{CodeComplete":null,"Project":"Coding","Team":"Batman","TimeSpent":"40","Children":[]}}
I belive this is like a string, since _SESSION[0] outputs "{". However, I want it to be an array or an object. The Array looks like this in php:
_SESSION( "items" => array(
221163 =>
array( CodeComplete => null
Project => "Coding"
Team => "Mail"
Timespent => "25"
Children => array(
)
)
221165 =>
array( CodeComplete => null
Project => "Coding"
Team => "Stones"
Timespent => "40"
Children => array(
)
)
)
)
I want to be able to access this array in the same way as I can in php (not litterary ofcorse) but _SESSION["items"] or _SESSION.items is undefined as _SESSION is a string...
Any ideas of what I'm doing wrong?
Just as #CD001 suggested in his comment, I removed the '' from the transfer so that it became
_SESSION = <?php print json_encode($_SESSION) ?>;
instead and now everything works fine, thank you!

using AJAX query to pass javascript array to php

After reading through quite a few posts here, (and even just straight copying code,) I still cannot figure out why this is not working.
On my main page, I have a textbox that a user pastes data into. Upon paste, this script runs (this and the ajax query below are in the same script function):
var lines = $('textarea').val().split('\n'); //create array from pasted data
I now have a JavaScript array with the pasted data. I'm trying to send this over to a separate PHP file that I will load into a div on this main page by doing the following:
$.ajax({
type: 'POST',
url: 'return.php',
data: {lines:lines},
success:function(data){
$("#info").load("return.php");
}
});
for (i=0; i < lines.length; i++) { // log the output
if (lines[i]){
console.log("line ", i , lines[i]);
}
}
In my return.php file, I have this:
$lines = $_REQUEST['lines'];
echo '<pre>';
echo($lines);
echo '</pre>';
My console.log is outputting the array perfectly, but for some reason it is not making its way over to return.php, as my echo is blank.
What am I doing wrong?
The response I get from return.php is:
<pre>testArrayArray
(
[0] => DL4004-13-F
[1] => S1G-13-F
[2] => ZXMP3A13FTA
[3] => B260A-13-F
[4] => S1J-13-F
[5] => S3B-13-F
[6] => SSN1N45BTA
[7] => GBJ1010-F
[8] => BPW20RF
[9] => T3035H-6I
[10] => ZXMP7A17KTC
[11] =>
)
</pre>
The success handler on your ajax request is calling return.php with nothing and loading it into #info.
Change success to instead do:
$("#info").html(data)
The $lines variable in your PHP code is an array, not a string. If you have the errors turned on, PHP should warn you that you're doing an "Array to string conversion" (at least it does for me using your code).
You can't echo an array like that, you have to iterate through the results somehow.

Populating Google Map Markers from PHP array using json_encode

When I use the hard coded javascript array as input for the map markers the markers show up just fine, so I know that the code I'm using to display the markers is good.
My problem is when I try and convert a php multi-array using json_encode, nothing shows up on the map.
The hard coded markers are:
var locations = [
['Sausalito', 37.8590937, -122.4852507,'url'],
['Sacramento', 38.5815719, -121.4943996,'url'],
['Soledad', 36.424687, -121.3263187,'url'],
['Shingletown', 40.4923784, -121.8891586,'url']
];
and they work.
The php array is:
$locations = array(array(Sausalito, 37.8590937, -122.4852507,'url'),array(Sacramento, 38.5815719, -121.4943996,'url'));
which produces the array,
Array
(
[0] => Array
(
[0] => Sausalito
[1] => 37.8590937
[2] => -122.4852507
[3] => url
)
[1] => Array
(
[0] => Sacramento
[1] => 38.5815719
[2] => -121.4943996
[3] => url
)
)
so no problem as yet.
Now when I json_encode the above array
var locations = '<?php echo json_encode($locations); ?>';
it does not get read by the javascript map code. and if I print the variable
document.write(locations);
it shows up as
[["Sausalito",37.8590937,-122.4852507,"url"],["Sacramento",38.5815719,-121.4943996,"url"]]
which kinda looks like the hard-coded above, but it does not get read by the map code which works with the hard-coded data.
Can anyone assist me, please, much appreciated.
Remove the single-quotes, otherwise locations will be a string and not an array:
var locations = '<?php echo json_encode($locations); ?>';
//--------------^--------------------------------------^

Creating a JSON array starting with index 1

I need to create a JSON array starting with index 1
Here is my code which picks the images from the websites
$image_urls = array();
//get all images URLs in the content
foreach($get_content->find('img') as $element)
{
/* check image URL is valid and name isn't blank.gif/blank.png etc..
you can also use other methods to check if image really exist */
if(!preg_match('/blank.(.*)/i', $element->src) && filter_var($element->src, FILTER_VALIDATE_URL))
{
$image_urls[] = $element->src;
}
}
//prepare for JSON
$output = array('title'=>$page_title, 'images'=>$image_urls, 'content'=> $page_body);
echo json_encode($output); //output JSON data
data.images gives the array bu it starts with 0
Try
$output = array();
$output['1'] = array('title'=>$page_title, 'images'=>$image_urls, 'content'=> $page_body);
echo json_encode($output); //output JSON data
Output would be:
{"1":{"title":(*page_title*),"images":(*img_url*),"content":(*page_body*)}}
Try using array_unshift
$image_urls = array_unshift($image_urls,null);//add an element at the zeroth index
unset($image_urls[0]);//remove the zero index
An single line solution to the image_url array:-
$arr=array(1,2,3,4,5,6);
$arr = array_combine(range(1, count($arr)), $arr);
echo '<pre>';print_r($arr);
Output :
Array
(
[1] => 1
[2] => 2
[3] => 3
[4] => 4
[5] => 5
[6] => 6
)

Categories

Resources