Convert the contents of the uploaded file to a JSON format

I've recently started using angularjs for file uploads and came across this helpful model on github: https://github.com/danialfarid/angular-file-upload

The file upload process is working smoothly for me. However, I'm facing a challenge after uploading the file - I want to retrieve the file contents in JSON format and then iterate over the JSON object using AngularJS. Unfortunately, I'm unsure of how to achieve this.

Below is the snippet of my code:

$filename = $_FILES['file']['tmp_name'];
$csv = array_map('str_getcsv', file($filename));
foreach($csv as $c)
{
    echo str_replace(array('"', ';'), ' ', $c[0]) . "\n";
}
    //How do I return as JSON here?

Also, here is my controller:

as.controller('Marketing', function($scope, $http, $upload)
{
    $scope.onFileSelect = function($files) {
        var file = $files[0];
        if (file.type.indexOf('image') == -1) {
            $scope.error = 'Image extension not allowed, please choose a JPEG or PNG file.'            
        }
        if (file.size > 2097152){
            $scope.error ='File size cannot exceed 2 MB';
        }     
        $scope.upload = $upload.upload({
            url: 'partials/result.php',
            data: {},
            file: file,
        }).success(function(data, status, headers, config) {
            // File uploaded successfully
            console.log(data);
            $scope.result = data;
        });
    }
});

I am trying to convert the data into a JSON object. Can anyone guide me on how I can accomplish this? My attempts with json_encode in PHP have been unsuccessful so far.

If anyone has insights on this matter, I would greatly appreciate your help.

Answer №1

This could be the solution you've been searching for

if(isset($_FILES["file"])){
    $filename = $_FILES['file']['tmp_name'];
    // ...
    if(move_uploaded_file($filename, "uploads/" . $fname)){

        // method A
        $csv_data = file_get_contents($filename);
        $parsed_array = array_map("str_getcsv", explode("\n", $csv_data));
        echo json_encode($parsed_array);

        // alternative approach; consider delimiter
        $first_row = str_getcsv($csv_data, "\n");
        $row_count = count($first_row);
        for($j = 0; $j < $row_count; $j++){
            $data_values = str_getcsv($first_row[$j], ";");
            $final_array[] = $data_values; 
        }
        echo json_encode($final_array);
    }
    // ...
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Display HTML content using AJAX within a div element

Within my HTML code, I have the following: <li class="register"><a href="">Registreer</a></li> as well as <div id="content"> </div> I attempted to load an HTML file into the div using the code below in the header se ...

Add a fresh item to a list using jQuery

Attempting to add a new list item using jQuery. In this scenario, the process works well, but when attempting to retrieve the value of an input field using .val(), no list item is created. http://www.example.com Code snippet: $(document).ready(functi ...

React: Submit button not triggering form submission despite having a valid submit event handler and correct syntax

My question stands out from existing ones as it features valid syntax, correct use of type="submit" on the button, and a simple onSubmit handler on the form. Despite this, clicking the button fails to trigger the onSubmit handler. To illustrate ...

Steps for generating a nested JSON structure using a pandas dataframe in Python

I have a pandas dataframe that contains logs from Windows 10. I need to convert this pandas dataframe into JSON format. What is the most efficient way to accomplish this? I've managed to generate a default pandas dataframe, but it's not nested t ...

Exploring AngularJS Service: simulating $rootElement and $rootScope for testing purposes

Currently, I am in the process of writing tests for a service responsible for updating meta information on a page. mod.service('MetaSrv', ['$rootScope', '$rootElement', function ($rootScope, $rootElement){ return { updat ...

Executing a function with arguments within a separate function

I've been working on creating a scheduler function that can randomly call another function with parameters. Here's the JavaScript code I have so far: function scheduleFunction(t, deltaT, functionName) { var timeout; var timeoutID; ...

enigmatic issue arising in Angular/Node

Could someone please shed some light on what might be causing the issue in my code? Thank you in advance! webpack: Compilation Failed. My Angular CLI: 1.6.3 Node: 8.9.4 OS: Windows 32-bit Angular: 5.2.1 Error Message: ERROR in ./node_modules/css-loader ...

Removing border of the top and bottom of jspdf pages

In my project, I am utilizing a combination of html2canvas, canvg, and jspdf to convert HTML content (which includes SVG graphs) into canvases for the purpose of creating a PDF file. To address some page-break issues, I have resorted to creating multiple c ...

Ways to identify when a React child element is overflowing

tl;dr How can I create a component that hides overflow and toggles views with a button? For example, the user can initially see tabs 1, 2, and 3 while tabs 4, 5, and 6 are hidden. Clicking a button will hide tabs 1, 2, and 3, and show tabs 4, 5, and 6 with ...

Storing the radio button's selected value in local storage using Vue JS

I have a pair of radio buttons that are linked together to accept a boolean value, either true or false. I am trying to implement a functionality where the selected value is stored in local storage. For example, if true is chosen, then true will be saved i ...

Ways to determine the presence of a value in an array using AngularJs

I'm currently working on looping through an array to verify the existence of email, phone, and alternate phone in a database. My challenge lies in finding a suitable function or workaround in AngularJS that allows me to iterate through the array with ...

How does setting $.support.cors = true; affect the performance of ajax calls on browsers that do not support Cross-Origin Resource Sharing (

Hey everyone, I've encountered a situation where I need to make cross-domain AJAX requests, so I included the line "$.support.cors = true;" before my ajax calls. However, I'm noticing that for non-cross domain calls, my ajax requests don't ...

Check for any empty or null values and cycle through various keys in JQ

Exploring methods to modify a json file obtained from a web service using jq, specifically focusing on reducing depth levels and retaining selected values. https://jqplay.org/s/_RZNr_oYwE This is a sample of the json structure: [ { "date":"2020-04- ...

Scrolling horizontally in vue-chartjs-chartwidget

I have a question regarding vue-chartjs. I am looking to achieve a similar result to the one demonstrated in this jsfiddle example: http://jsfiddle.net/mbhavfwm/ Below is the code for my Vue.js component (Chart data is passed through params). &l ...

Easy methods to navigate between screens without using React Router libraries

After experimenting with two different methods to switch between screens in a simple application (up to 3 modes/screens), I am still in the learning phase and mainly focusing on practicing with useState and possibly useEffect for certain scenarios. I&apos ...

fetching a set of data entries from an entity on dynamic CRM platform utilizing the REST API along with asynchronous JavaScript and XML

Seeking to display all accounts from the account entity in an alert box by making an ajax call to the Service OrganizationData.svc. The post method works fine for adding an account, but when trying to retrieve all accounts using GET, I encounter some diff ...

How can I efficiently remove elements from the end of an array in Vue.js?

Is there a way to splice data starting from the back with a higher index? When clicking on the .delete div, how can I make it so the .image-box div deletes starting from the end? I need help implementing this feature in my code. Here is a snippet: < ...

Prohibit the emission of null values in a WebAPI OData v4 service to ensure data integrity

I am currently operating a WebAPI OData v4 service and I have a requirement to exclude null values from the output. For instance, when a User object is requested, the response includes the following information: "value": [ { "FirstName": "John", "Last ...

Issues encountered when trying to use default color classes in Tailwind CSS

I'm currently working on a React project that utilizes the Tailwind CSS Framework. To integrate Tailwind into my React app, I used NPM to install it in the following way: npm install -D tailwindcss postcss autoprefixer npx tailwindcss init -p After i ...

"Ensuring Proper Validation for Forms with JavaScript: A Step-by-Step Guide

Here is a sample Javascript form: <form id="loginForm" name="loginForm" action="/create_session/" method="post">{% csrf_token %} <table border="0" cellpadding="0" cellspacing="0" id="id-form"> <tr> <th valign=" ...