using php to convert csv to xml for use in Javascript - javascript

I am a newbie to scripting and am trying to use the following php code (taken from another post that was already answered: PHP Script to convert .CSV files to .XML, to convert csv data to xml (I named this file csv2xml.php). I am trying to pull the outputted xml file that is created in the php script into javascript using the DownloadURL function so that I can parse the data further, but I'm not sure if I can use a php file in the downloadURL function in order to parse it. Can anyone point me in the right direction? I have to have this done by tomorrow so any help would be appreciated. PHP code is first, followed by the section of javascript I am referring to.
<?php
error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', true);
ini_set('auto_detect_line_endings', true);
$inputFilename = 'input.csv';
$outputFilename = 'output.xml';
// Open csv to read
$inputFile = fopen($inputFilename, 'rt');
// Get the headers of the file
$headers = fgetcsv($inputFile);
// Create a new dom document with pretty formatting
$doc = new DomDocument();
$doc->formatOutput = true;
// Add a root node to the document
$root = $doc->createElement('rows');
$root = $doc->appendChild($root);
// Loop through each row creating a <row> node with the correct data
while (($row = fgetcsv($inputFile)) !== FALSE)
{
$container = $doc->createElement('row');
foreach ($headers as $i => $header)
{
$child = $doc->createElement($header);
$child = $container->appendChild($child);
$value = $doc->createTextNode($row[$i]);
$value = $child->appendChild($value);
}
$root->appendChild($container);
}
echo $doc->saveXML();
?>
downloadUrl("csv2xml.php", function(data) {
var xmlDoc = xmlParse(data);
var records = xmlDoc.getElementsByTagName("row");
...(parsing code)

Related

Passing a JSON file to a php server and then save the data from it into a Mysql DB

As the tittle says i'm coding a web app as part of a school project. My goal is for someone to upload a json file and save some data of it in a table on Mysql for further functionallity in the app.
My question is how exaclty can you pass a JSON file to PHP and then parse it from there as to store the wanted data to the DB. I tried sending it with the help of Jquery fileupload as the json files may be quite large and on the php side i used the function file_get_contents but i had no luck with it.
Here is my javascript code :
$(document).ready(function () {
$("#submitupload").click(function(){
var files = $("#files");
$("#uploadedfile").fileupload({
url: 'upload.php',
dataType: 'json',
autoUpload: false
}).on('fileuploadadd', function (e, data) {
var fileTypeAllowed = /.\.(json)$/i;
var fileName = data.originalFiles[0]['name'];
var fileSize = data.originalFiles[0]['size'];
console.log(data);
if (!fileTypeAllowed.test(fileName)){
$("#error").html('Only json files are allowed');
}else
data.submit();
}).on('fileuploaddone', function (e , data){
var msg = data.jqXHR.responseJSON.msg;
$("#error").html(msg);
}).on('fileuploadprogress', function (e,data){
var progress = parseInt(data.loaded / data.total * 100, 10 );
$("#progress").html("Completed: " + progress + "%");
})
})
})
And here is the PHP :
<?php
include_once ('connection.php');
if (isset($_FILES['uploadingfile'])){
$file = $_FILES['uploadingfile'];
$data = file_get_contents($file);
$array = json_decode($data, true );
foreach( $array as $row){
$sql = "INSERT INTO locations(timestamp) VALUES ('".$row["timestampMs"]."')";
mysqli_query($conn, $sql);
}
$msg = array("msg" => "times ok ");
exit(json_encode($msg));
}
Noticed the error in file_get_contents() that says that the $file variable is an array not a string so i tried to pass the $_FILES variable as an argument with no luck again.
Is this the correct way to way to do it and if yes what am i missing or should i use another approach?
Thanks for the long read and your time in advance ! Sorry if any of this sounds stupid but im new to PHP .
$_FILES['uploadingfile'] is an array with several pieces of information about the uploaded file. So you need to use:
$file = $_FILES['uploadingfile']['tmp_name'];
to get the filename where the data is stored.
See Handling File Uploads for full details.

Access javascript variables on server php file via browser javascript

using javascript code in browser to access javascript variable in server php file
( the php file search a text file and returned result as a php variable, then I set that php variable as javascript variable)
//php file on server called data.php
<?php
$search = 'bing';
// Read from file
$lines = file('text.txt');
$linea='';
foreach($lines as $line)
{
// Check if the line contains the string we're looking for, and print if it does
if(strpos($line, $search) !== false) {
$liner=explode(': ',$line);
$linea.= $liner[1];
}
}
echo 'Search returned: '. $linea;
<script type=\"text/javascript\">
var varxxx = $linea;
</script>
?>
//text file on server
foo: bar
el: macho
bing: bong
cake color: blue berry
mayo: ello
//Java script code in browser.
var xhr = new XMLHttpRequest();
xhr.open("GET","http://.........data.php",false);
xhr.send(null);
$Variables.setValue(5, 'varxxx');
I got
reference error
x is not defined
if I just run http://.........data.php , it shows Search returned:"Bong"
it means data.php successfully returned the result, and php $linea is Bong.
so this part below in the php file is what causes the error?
<script type=\"text/javascript\">
var varxxx = $linea;
</script>
or something wrong with my Javascript code in browser?
Any help is appreciated
Thanks in advance
Try "echoing" the script tag to the .html body.
You're getting this error because the variable is being created on the server side only, thats why the variable is not defined. Also I recomend you to use let instead of var, let is more secure in terms of scope.
//php file on server called data.php
<?php
$search = 'bing';
// Read from file
$lines = file('text.txt');
$linea='';
foreach($lines as $line)
{
// Check if the line contains the string we're looking for, and print if it does
if(strpos($line, $search) !== false) {
$liner=explode(': ',$line);
$linea.= $liner[1];
}
}
echo 'Search returned: '. $linea;
?>
// New script
<?php
echo("<script> var varxxx = ".$linea." </script>")
?>

Reading file path from JSON to Javascript

Please, help with this. I generate a JSON string from database, like this
<?php
require_once "pdo.php";
$stmt = $pdo->query("SELECT * FROM locals WHERE article_id = {$_POST['idc']}");
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
echo(JSON_encode($row['article_image']));
And receiving in browser like this
$('#local').change(function(event){
locid = $(this).val();
$.post('mod/imgtour.php', {'idc':locid}, function(data){
window.console && console.log(data);
$.getJSON('mod/artic.php',function(data){
window.console && console.log(data);
$('#artimg').attr("src","data.first");
});
});
But in the console I realize that the data I recieve, which is the path to an image come in this way: "images\\locals\\article1.png" (the path stored in database is in this form "images\locals\article1.png" )
I need the file path comes in the right way, to replace it in the image tag...
Any suggestion?

Saving a file on server using JavaScript

Js code
var server = '';
var orig_chat = chatUpdateSucess;
chatUpdateSucess = function(o){
if (o.GlobalChats && o.GlobalChats.length > 0) {
//TODO: Add setting to enable/diosable this
console.log(JSON.stringify(o.GlobalChats));
var xhr = new XMLHttpRequest();
xhr.open("POST", server+"/api.php?request=log_gc");
xhr.send(JSON.stringify(o.GlobalChats));
}
orig_chat.apply(this, arguments);
};
Server code named api.php
<?php
header("Access-Control-Allow-Origin: *");
if(!empty($_POST['o.GlobalChats'])){
$data = $_POST['o.GlobalChats'];
$fname = time() . ".txt";//generates random name
$file = fopen("" .$fname, 'w');//creates new file
fwrite($file, $fclose($file);
}
?>
console.log output
[{"PlayerId":237186,"toPlayerId":0,"chatid":16606292,"added":"/Date(1451764948837)/","addedText":"20:02","PlayerLink":"p=Kodabear|237186|T?|78|1|0|0-144-0-240-186-0-0-0-0-0-0-0-0|#IKnowAFighter|Neurofibromatosis Awareness day/Month|5-404-282-59","text":"Exmaple of a real chat"}]
I created a js that sends a file to my server every time the chat in the game is updated. But I am having problems with the server side code any advice would be great help. (PHP code was founded here
Saving a text file on server using JavaScript
Try to var_dump($_POST['o.GlobalChats']) to see if your data is reaching the server.
It seems like you are not writing the file to the system properly. Please read the examples at the manual (http://php.net/manual/pt_BR/function.fwrite.php)
Also, using time() is not safe, because two files may be created at the same UNIX timestamps in extreme cases, and one will overwrite the other
Try something like this:
$data = $_POST['o.GlobalChats'];
$fname = time() . "-" . rand ( 1 , 10000 ) . ".txt";
$handle = fopen($fname, 'w');
fwrite($handle, $data);
fclose($handle);

fullcalendar.js is not reading the php json feed

i want to pre-poulate my fullcalendar instance via a php json feed.
The page is loading fine (no 404 or sth like that) but the calendar is not showing any of the events.
generating the json:
<?php
require("../config/config.php");
$uid = $_SESSION['uid'];
$res = $db->query("SELECT * FROM slots WHERE tid = '$uid'");
$data = array();
while($row = $res->fetch_assoc())
{
$event = array();
$event['editable'] = false;
$event['id'] = "fixE_".$row['id'];
$event['title'] = getSlotStatus($row['status']);
$event['sid'] = $row['sid'];
$event['status'] = $row['status'];
$event['start'] = $row['start'];
$event['end'] = $row['end'];
$event['standby'] = $row['standby'];
if(strpos($data['status'],"_old"))
{
$event['textColor'] = '#000000';
$event['color'] = '#cccccc';
$event['className'] = 'lessonSlotOld';
}
else
{
$event['color'] = getColorCode($row['status']);
if($row['standby'])
{
$event['borderColor'] = '#0000FF';
}
}
$data[] = $event;
}
echo json_encode(array("events"=>$data));?>
and here's the part of the fullcalendar code where i am inserting the feed:
events:
{
url: 'include/fetchSlots.php',
type: 'POST',
error: function(){alert("There was an error fetching events")}
},
the json output of the php looks like the following (this is just a part because the whole response would be too much ;) )
{"events":[{"editable":false,"id":"fixE_164","title":"Slot is closed","sid":"0","status":"closed","start":"2015-06-06T04:00:00+08:00","end":"2015-06-06T04:30:00+08:00","standby":"0","color":"#B20000"}]}
Ok so here's the solution/the mistake.
The only problem that fullcalendar has is the line where the actual json is posted:
echo json_encode(array("events"=>$data));
fullcalendar doesnt want the "events" and it doesnt want the twice wrapped array. so the solution to this is simply to output the data-array directly:
echo json_encode($data);
then, the events are all loaded correctly.
ah and for all watchmen out there, yes i found the mistake with the wrong named variable ;)
if(strpos($data['status'],"_old"))
to
if(strpos($row['status'],"_old"))

Categories