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

Search form with a variety of fields that allows for searching without needing to repeat the component for each condition

I am currently facing an issue with my form that consists of multiple fields, each used to search through an API and display matching data in a table below. While I have successfully implemented this for one field, I now need it to work for all fields with ...

What could be the reason why a specific item is not being retrieved by its ID?

Whenever I navigate to the route: '/gallery', all the items from the file './posts.json' are fetched and displayed on the screen. However, upon navigating to the route: '/gallery/:id', my intention is to retrieve a single item ...

Tips for successfully uploading FormData files using Axios: Resolving the TypeError of "file.mv is not a function"

When transmitting a file from one server to another using Axios, I am facing an interesting scenario where one server is an app backend and the other is a blockchain server. The destination for the file transmission is set up as follows: router.post("/a ...

Adding images to HTML using JavaScript below existing images

I'm currently working on a JavaScript game and I want to implement a feature where my character can move under blocks (isometric PNG images) instead of just sliding through them. Is there a way to dynamically adjust my character's position in the ...

Positioning a designated div directly above a designated spot on the canvas

I'm grappling with a challenge in my game where the canvas handles most of the animation, but the timer for the game resides outside the canvas in a separate div. I've been struggling to center the timer around the same focal point as the squares ...

Is d3 Version pretending to be a superior version?

I have encountered an issue with my project that involved using d3 v5.5.0. After transferring it to a different computer and running npm install, the application now seems to be recognizing d3 as a higher version? A crucial part of my program relies on th ...

The onclick event is malfunctioning in Chrome when dealing with data driven by SQL

<select id='city' name='city' > <?php $dbcon = mysql_connect($host, $username, $password); mysql_select_db($db_name,$dbcon) or die( "Unable to select database"); $city_query = "SELECT city,county FROM citycatalog order by city ...

Positioning the div to align perfectly alongside the list items

My current objective involves dynamically creating div elements and populating them with items. A working demo of my progress can be found by following this link. The issue at hand is that the newly created div does not appear in the desired location, but ...

What is the best way to retrieve an object value within an if statement?

What can I do to ensure that the line within the if statement functions properly? const player1 = { name: "Ashley", color: "purple", isTurn: true, play: function() { if (this.isTrue) { return `this["name"] is current ...

The CSS styling for a pie chart does not seem to be functioning properly when using jQuery's

https://i.stack.imgur.com/kEAKC.png https://i.stack.imgur.com/03tHg.png After examining the two images above, it appears that the CSS is not functioning properly when I try to append the same HTML code using JavaScript. Below is the snippet of my HTML co ...

Enhancing appearance with $refs?

Having trouble adding style to the $refs attribute. I keep getting an error message saying "Cannot set property 'cssText' of undefined." Is there a way to accomplish this task? I haven't come across anything similar to this issue before. th ...

Using jquery to transition an image to fade out and then reappear in a different position

There is an image in a div with the highest z-index. Upon clicking on something, the image should fade out and then fade in at a specified position below another image with the class "aaa". The current approach involves using jQuery to fade out the image ...

In React, the functionality of rendering components conditionally is not functioning properly

I am looking to conditionally display either the Login component or Menubar component based on the value of the isLogin state. If the isLogin state is false, I want to render the login page. If it is true, I want to render the Menubar page. To achieve thi ...

The custom pagination feature in Addsearch UI always default to displaying the first page of search

I am currently using addsearch-ui version 0.7.11 for my project. I have been attempting to integrate a customized pagination function based on this example template. However, I have encountered an issue where the arrow buttons always navigate to the first ...

Adding the highcharts-more.src.js file to an Angular 2 project: A step-by-step guide

I have linked highcharts-more to the system variable: 'highcharts-more': 'node_modules/highcharts/highcharts-more.src.js' But I keep getting an error message saying: Error in dev/process/templates/detail.template.html:40:33 ORIGINAL ...

What could be causing me to have to click the button twice in order to view my dropdown list? Any suggestions on how to

I am facing an issue where I have to click twice on the "Action" button in order to see my dropdown list. How can I resolve this? Is there a way to fix it? $(document).ready(function() { $(".actionButton").click(function() { $dropdown = $("#cont ...

AngularJS throwing error due to additional content following the document element during XML parsing

I've been working with Angular JS and recently created a basic login form with routing to navigate to the next page upon successful login. However, I've encountered an issue when trying to implement conditional routing. Although I can successful ...

Is it possible to utilize a JavaScript variable as a node in a JSON stringification request?

After successfully retrieving data from the Bungie API previously, I am now facing a challenge in reading a specific JSON file. http://prntscr.com/k3tin3 I'm currently stuck on how to extract a node from the JSON and then utilize it to request charac ...

What is the method for accessing an image in JavaScript?

Currently, I am developing a currency converter for a gaming marketplace and I would like the users to be able to generate images using JavaScript. While most of the work is completed, I am facing an issue where the images are not displaying properly and i ...

Reload the text content of a locally hosted webpage within an iframe at regular intervals

I have set up a simple webpage on my local machine to showcase the contents of some text files on a dedicated monitor. However, I am facing an issue where refreshing the entire webpage causes flickering. My goal is to only refresh the iframes and reload t ...