I have a csv file that I want transfer into JSON but it doesn't work the way I was hoping
PHP
$file = $_FILES['csv']['tmp_name'];
$csv= file_get_contents($file);
$array = array_map('str_getcsv', explode(";", $csv));
echo "<script type='text/javascript'>alert('OK!');</script>";
javascript
var myJsarray = <?= json_encode($array); ?>;
alert(myJsarray[0][0]);
my csv looks something like this
aaa;46
bbb;23
ccc;51
ddd;23
and my output looks like this
[["aaa"],["46\r\nbbb"],["23\r\nccc"],["51\r\nddd"],["23"]];
and I was hoping to get
[["aaa"],["46"],["bbb"],["23"],["ccc"],["51"],["ddd"],["23"]]
my idea was to put "$csv=explode("\n", $csv)" under "$csv= file_get_contents($file); "
But it gave me error that "$csv is not a string.
http://jdl-enterprises.co.uk/sof/25763045.php
If it's something like this that you want:
$csv= file_get_contents($file);
$array = explode("\r\n", $csv); // Update this to \n if need be or however you csv saves it
for($i=0;$i<count($array);$i++){
$array[$i] = explode(';', $array[$i]);
}
This will produce:
[["aaa","46"],["bbb","23"],["ccc","51"],["ddd","23"]]
And if you want it like your example, add into the code:
$array2 = array();
foreach($array as $ar) {
foreach($ar as $a) {
$array2[] = $a;
}
}
This will produce:
["aaa"],["46"],["bbb"],["23"],["ccc"],["51"],["ddd"],["23"]
Obviously there is a set of [ ] missing around the whole code, but you could stuff it all inside another array, or just add them manually.
Your "CSV" is in an incorrect format:
aaa;46 bbb;23 ccc;51 ddd;23
Change it to:
aaa,46 bbb,23 ccc,51 ddd,23
You do know there is a function just for reading CSV in PHP? It's called fgetcsv()
$data = array();
$fh = fopen('file.csv', 'r');
while (($line = fgetcsv($fh, 0, ';')) !== false) {
$data[] = $line;
}
fclose($fh);
echo json_encode($data);
Related
I'm utilizing PHP to stringify input from my form to a JSON. It's currently formatting it like this
{"name":"asfd","username":"awsf","email":"kean","age":"21","gender":"Male","submit":"Submit"},
{"name":"asdf","username":"asfd","email":"asdf#asdf","age":"21","gender":"Male","submit":"Submit"},
But it should look more like this, right?
[
{"name":"asfd","username":"awsf","email":"kean","age":"21","gender":"Male","submit":"Submit"},
{"name":"asdf","username":"asfd","email":"asdf#asdf","age":"21","gender":"Male","submit":"Submit"}
]
Here is my current php. What should I do to make it stringify correctly?
<?php
if (isset($_GET['name'])){
$json_data = json_encode($_GET);
// var_dump($json_data);
$file = file_put_contents('data.json', $json_data."," , FILE_APPEND |
LOCK_EX);
?>
<script type="text/javascript">
ChangeName(<?php echo("'".$_GET['name']."'") ?>);
</script>
<?php } ?>
The only way to do this is to read data from the file first, decode it, append the new array to that data and encode it again to json and put it in the file, sort of like this:
<?php
if (isset($_GET['name']))
{
$data = json_decode(file_get_contents('data.json'), true);
$data[] = $_GET;
$json_data = json_encode($data);
$file = file_put_contents('data.json', $json_data);
}
I have tried other questions on the same issue to retrieve data from JSON. But none of them worked for me as my JSON data is different from others.
Maybe my question sounds same as others questions, but I have tried everything.
[
{
"bHeader":{
"ei":"NSE",
"seg":"I"
},
"cNetChangeIndicator":"\u0000",
"fClosingIndex":10558.5,
"fHighIndexValue":10532.0,
"fIndexValue":10469.0,
"fLowIndexValue":10438.5,
"fOpeningIndex":10499.5,
"fPercentChange":-0.85,
"sIndexName":"962450",
"fChange":-89.5,
"iIdxId":311
}
]
Please help me out in finding the values
fIndexValue
fChange
fPercentChange.
Try the following:
var data = [{"bHeader":{"ei":"NSE","seg":"I"},"cNetChangeIndicator":"\u0000","fClosingIndex":10558.5,"fHighIndexValue":10532.0,"fIndexValue":10469.0,"fLowIndexValue":10438.5,"fOpeningIndex":10499.5,"fPercentChange":-0.85,"sIndexName":"962450","fChange":-89.5,"iIdxId":311}];
data.forEach(function(item){
console.log('fIndexValue:'+ item.fIndexValue);
console.log('fChange:'+ item.fChange);
console.log('fPercentChange:'+ item.fPercentChange);
});
Updated
You can use json_decode(json_string, true) php function like below
$str = '[{"bHeader":{"ei":"NSE","seg":"I"},"cNetChangeIndicator":"\u0000","fClosingIndex":10558.5,"fHighIndexValue":10532.0,"fIndexValue":10469.0,"fLowIndexValue":10438.5,"fOpeningIndex":10499.5,"fPercentChange":-0.85,"sIndexName":"962450","fChange":-89.5,"iIdxId":311}]';
$arr = json_decode($str, true);
print_r($arr);
echo $arr[0]['fIndexValue'];
echo $arr[0]['fChange'];
echo $arr[0]['fPercentChange'];
For refresh page every 30s. write code below.
// write the function
function refresh($time)
{
$current_url = $_SERVER[ 'REQUEST_URI' ];
return header( "Refresh: " . $time . "; URL=$current_url" );
}
// call the function in the appropriate place
refresh(30);
// this refreshes page after 4 seconds
have you try with JSON.parse(request)? you will be able to acces as an object
You can do the following:
$data = '[
{
"bHeader":{
"ei":"NSE",
"seg":"I"
},
"cNetChangeIndicator":"\u0000",
"fClosingIndex":10558.5,
"fHighIndexValue":10532.0,
"fIndexValue":10469.0,
"fLowIndexValue":10438.5,
"fOpeningIndex":10499.5,
"fPercentChange":-0.85,
"sIndexName":"962450",
"fChange":-89.5,
"iIdxId":311
}
]';
$data = json_decode($data);
foreach ($data as $d){
echo $d->fIndexValue;
echo $d->fChange;
echo $d->fPercentChange;
}
your json is 2 dimension so you should try something like
data[0]['fHighIndexValue']
looking in fiddle
http://jsfiddle.net/scnx3vh4/
I am working on a project that requires create hundreds of variables in javascript with PHP values. I can write each one line by line like so:
var M1 = <?php echo json_encode($$mn[0]); ?>;
var M2 = <?php echo json_encode($$mn[1]); ?>;
var M3 = <?php echo json_encode($$mn[2]); ?>;
As I said there are hundreds of these though and if it is possible to do in a loop I would be very interested in learning. I have searched all over and can't find a direct answer. It may very well be that this is not possible. I am new to coding and still learning what certain code can and cannot do.
Any insight or direction on this topic would be greatly appreciated!
If this is not an option is it possible to use an array index for the javascript variable name? I have created an array for the JS and PHP. The PHP works fine above but if I try to use an array index for the JS like below, it breaks:
var mcirc[0] = <?php echo json_encode($$mn[0]); ?>;
I have output the array and the values are coming up correctly but when I run this I get the message:
[object HTMLDivElement]
instead of the actually value that should show up.
UPDATE
$mn array:
for ($m1 = 1; $m1 < 6; $m1++) {
$mn[] = 'M'.$m1;
}
UPDATE
Select SQL creating array:
$sqlMC = "SELECT * FROM tblmaincircles";
$result = $conn->query($sqlMC);
while($row = $result->fetch_assoc()) {
$$row["mcID"]= $row["mcName"];
}
The array for mcID looks like this:
M1 = "text1"
M2 = "text2"
M3 = "text3"
M4 = "text4"
M5 = "text5"
UPDATE
end result desired:
var M1 = "text1";
var M2 = "text2";
var M3 = "text3";
var M4 = "text4";
var M5 = "text5";
Where "text1, ...2, ...3, ...4, ...5" are coming from the MySQL database.
UPDATE
Here is the final code that got this working:
$sqlMC = "SELECT mcID, mcName FROM tblmaincircles";
$result = $conn->query($sqlMC);
while($row = $result->fetch_assoc()) {
$mcID[] = $row["mcID"];
$mcName[] = $row["mcName"];
}
<?php for ($m1 = 0; $m1 <5; $m1++) { ?>
var <?php echo $mcID[$m1]; ?> = <?php echo json_encode($mcName[$m1]); ?>;
<?php } ?>
Simply put JSON into variable
var json = <?php echo json_encode($$mn); ?>;
And then process the JSON way you want:
eg.
var json=[{key:someValue},
{key:someValue2},
{key:someValue3}
];
json.forEach(function(a){
console.log(a.key);
})
First in your query part, declare a variable to hold the result that you want. I'm assuming the M1 is mcID in your table and text1 is the mcName. For example:
$sqlMC = "SELECT * FROM tblmaincircles";
$result = $conn->query($sqlMC);
$mac = [];//or $mac = array(); Depends on your PHP version.
while($row = $result->fetch_assoc()) {
$mac[$row["mcID"]] = $row["mcName"];
}
And then, iterate through the $mac array with foreach loop. I'm assuming you are using PHP codes within HTML. The $key will be the mcID and the $value will be the mcName.
//php tag for the foreach opening
<?php foreach ($mac as $key => $value) { ?>
var <?php echo $key; ?> = <?php echo "'$value';"; ?>
//php tag for the foreach closing
<?php } ?>
OR, if you want to use javascript associative array.
var macJs = {};
<?php foreach ($mac as $key => $value) { ?>
macJs.<?php echo $key; ?> = <?php echo "'$value';"; ?>
<?php } ?>
And you can access the element like this in javascript macJs.M1.
You should use JSON to 'export' your objects/array through different languages, in that case:
var json = '<?= json_encode($your_array); ?>';
After this you can parse this Json, what should return your array:
var your_array = JSON.parse(json);
Environment
Windows 8.1 64bit
Google Chrome
What I'm trying to do
Ultimate goal
Make a pet monitoring system using Raspberry Pi. Create a webpage where you can check streaming image of a pet and the temperature and humidity.
Current issue
Can't read csv data (temperature and humidity) using PHP and pass it to javascript in a html file.
The following gives me a blank page.
test.html
<?php
$data = array();
$fp = fopen('temphumid.csv', 'r');
$row = fgetcsv($fp); // skip the header
while ($row = fgetcsv($fp)) { $data[] = sprintf("['%d', %d, %d] ", $row[0], $row[1], $row[2]); }
$str = implode(', ' . PHP_EOL, $data);
?>
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([ ['day', 'avg_temp', 'avg_humid'],
<?php $str; ?>
]);
var options = { title: 'This is a test graph' };
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div" style="width: 80%; height: 400px;"></div>
</body>
</html>
temphumid.csv is in the same directory as test.html.
temphumid.csv
dateandtime,temp,humid
1,20.0701749938488,48.0275514992728
2,20.2401044696121,57.2354245801184
3,19.1474087424506,45.5657495890199
4,18.8319188605772,62.4405658353862
5,20.8854516366497,46.5185590247232
6,20.7459481702926,47.4137986506082
7,20.9609524855751,48.5064890268627
8,17.0936718055156,46.1276393517355
9,18.4273511669417,42.4825830307023
10,20.9669696456074,51.5502032331834
I tried a lot of things including adding echo to php clause, hard-coding a sample array in javascript, etc... in vain.
Changing the line of <?php echo $str; ?> to [0, 5, 4], [1, 9, 10], [2, 20, 23] works fine. So there's something wrong with PHP but I can't figure out what it is.
I also referred to this post.
- How to pass variables and data from PHP to JavaScript?
But this wasn't helpful.
Also, the javascript console told me the following message.
The console tells me Uncaught SyntaxError: Unexpected token <
How can I solve this issue? Thanks in advance.
update1
I added echo and ran the program in a web server in Raspberry Pi. However, I still see a blank page and Uncaught SyntaxError: Unexpected token < on console.
update2
I changed the extension to php and now it works fine. Thanks, folks!
Replace <?php $str; ?> with <?php echo $str; ?>, change the extension of your file to .php instead of .html, and everything will work well.
Maybe it's because the php file doesn't have a .php extension. Try renaming test.html in test.php.
Some similar code I wrote:
$seperator = $_POST['seperator'];
$escape = $_POST['escape'];
$default_val = $_POST['default_val'];
$files = $_FILES['filesToUpload']['name'];
$files_array = array();
//no files selected
if ($files[0] == "") {
echo "You have to select at least 1 file";
exit();
}
//preprocess by creating an array per file with it's path and name
$count = 0;
foreach ($files as $file) {
$current_file = array();
$current_file['name'] = $file;
$current_file['path'] = $_FILES['filesToUpload']['tmp_name'][$count];
$files_array[$file] = $current_file;
++$count;
}
$translation_array = array();
$languages = array();
foreach ($files_array as $file_key => $file_value) {
$text_file = file($file_value['path']);
$languages[] = $file_value['name'];
foreach ($text_file as $line_number => $line) {
$line = rtrim($line, "\n");
$line_parts = explode('=', $line);
$translation_key = $line_parts[0];
if ($file_value['name'] != 'brndportal.properties') {
$translation_array[$translation_key][$file_value['name']] = $line_parts[1];
} else {
$translation_array[$translation_key][$file_value['name']] = $line_parts[0];
}
}
}
$translation_csv = fopen("files/translation.csv", "w") or die("Unable to open file!");
//headers
$txt = "key" . $seperator;
foreach ($files as $file) {
$txt .= $file . $seperator;
}
$txt .= "\n";
fwrite($translation_csv, $txt);
//translations
foreach ($translation_array as $translation_key => $translation_arr) {
if (array_key_exists('brndportal.properties', $translation_array[$translation_key])) {
$txt = '';
$txt .= $translation_key . $seperator;
foreach ($languages as $language) {
if(array_key_exists($language, $translation_arr)) {
$translation_value = $translation_arr[$language];
}
else {
$translation_value = $default_val;
}
if (strpos($translation_value, $seperator) !== false) {
$translation_value = $escape . $translation_value . $escape;
}
$txt .= $translation_value . $seperator;
}
$txt .= "\n";
fwrite($translation_csv, $txt);
}
}
fclose($translation_csv);
It reads 1 or more CSV files and parse the lines. You can insert you own separator and stuff.
I think it would be best to read everything to arrays and serialize it to JSON, that way you can pass it to javascript with an ajax call. I'd suggest using jQuery for that part.
I had the same difficulty with Uncaught SyntaxError: Unexpected token < on the console.
The <?php echo $str; ?> solution works for certain variables. I had an array though.
So I used var myArray = <?php echo json_encode($myArray); ?> and it worked.
Currently I've similar to the following tree structure:
+images
+sub-directory
-image1.jpg
-image2.jpg
+sub-directory-2
-image3.jpg
-image4.jpg
-some-image.jpg
-another.jpg
<script>
<?php
//path to directory to scan. i have included a wildcard for a subdirectory
$directory = "images/*/";
//get all image files with a .jpg extension.
$images = glob("" . $directory . "*.jpg");
$imgs = '';
// create array
foreach($images as $image){ $imgs[] = "$image"; }
echo "var allImages = ".$imgs.";\n";
?>
console.log(allImages);
</script>
As I'm extremely new to php, I'm blindly getting logged as Array() in the console.
Also, I've set $directory = "images/*/"; which will get all images inside the subfolders only but not getting images inside parent directory that likely to images/some-image.jpg and I wanted to get this too.
I want all the images in an array like this (when I use console.log(allImages);):
['some-image.jpg','another.jpg','image1.jpg','image2.jpg','image3.jpg','image4.jpg']
I love JSON, keeps things nice and simple:
<?php
$images = glob("images/*/*.jpg");
$imgs = array();
foreach($images as $image){ $imgs[] = $image; }
?>
<script>
var allImages = JSON.parse('<?php echo json_encode($imgs);?>');
console.log( allImages);
</script>
Now you have the php array available in javascript, with the same structure. You can loop them with a for, of if you have jQuery, $.each().
I changed a code more to your style (mixing php and html), but you should try to split those in htmltemplates.
Im not 100% sure about this, but you can regex in your glob, if this works you don't need the foreach, this will return only the filenames:
$images = glob("~(?:images/*/)*\.jpg~");
What about this:
<script>
<?php
$directory = "images/*/";
$images = glob("" . $directory . "*.jpg");
echo "var allImages = ['".implode("', '", $images)."'];\n";
?>
console.log(allImages);
</script>
How about a recursive function?
function loadImages($folder)
{
$files = glob($folder);
foreach( $files as $file )
{
if(is_dir($file))
{
loadImages($file);
} else {
$images[] = $file; // add some file type validation here
}
}
return $images;
}
$images = json_encode(loadImages($startFolderPath));
I'm on an iPad so I can't test it.