I am posting a large array to a PHP file. The array looks like this:
var arr = ["Filename", "Annotationtag", "Upper left corner X", "Upper left corner Y", "Lower right corner X", "Lower right corner Y", "locationName",
"/var/www/html/projects/MasterImages/95-20180527-190018-205342-00002.jpg", "TShirtBackSide_Pepsi", 435, 123, 504, 151, "TShirtBackSide"];
Once this array is received by the PHP script, I want to split this array at every 7th element, move the rest of the values to subsequent lines and eventually write the split array to a csv file where each line contains 7 columns of data.
A short html file is as follows:
arraypost.php
<html>
<head>
<title>Test</title>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script type="text/javascript">
function pusharr() {
var arr = ["Filename", "Annotationtag", "Upper left corner X", "Upper left corner Y", "Lower right corner X", "Lower right corner Y", "locationName",
"/var/www/html/projects/MasterImages/95-20180527-190018-205342-00002.jpg", "TShirtBackSide_Pepsi", 435, 123, 504, 151, "TShirtBackSide"];
//Option1: var newarr = arr.toString();
//Option2: var newarr = JSON.stringify();
console.log(arr);
$.post("getAnnotationsForTF.php", { 'data' : arr }, function(output){
console.log(output);
});
}
</script>
</head>
<body>
<button onclick="pusharr()">Click</button>
</body>
</html>
getAnnotationsForTF.php
<?php
$lsData = isset($_POST['data'])?$_POST['data']:'';
$inputArray = explode(',',$lsData);
$cnt = count($inputArray);
$interval = $cnt/7;
$iArray = [];
$iArray = array_chunk($inputArray, $interval);
if(file_put_contents("files/test.csv", $iArray)) {
echo "Working";
} else {
echo "Not Working";
}
?>
While the csv file gets created, all I see in the csv file is:
ArrayArrayArrayArrayArrayArrayArrayArray
I tried various options. But not able to get through.
The desired output of csvfile is as follows:
Filename, Annotationtag, Upper left corner X, Upper left corner Y, Lower right corner X, Lower right corner Y, locationName
/var/www/html/projects/MasterImages/95-20180527-190018-205342-00002.jpg, TShirtBackSide_Pepsi, 435, 123, 504, 151, TShirtBackSide
file_put_contents()does not know how to write out an array!<?php error_reporting(E_ALL); ini_set('display_errors', 1);to see if it yields anything.fputcsvmaybe?fputcsv()will allow you to have each row as an array and just write the array directly to the file. Will require minimal effort for you to change, and it's designed for this exact issue :)file_put_contents("files/test.php", '<?php return '.var_export($array, true).';')and then do$array = require 'files/test.php'Just saying...