Thursday, December 30, 2021

Read a CSV to Array in PHP

Read a CSV to Array in PHP

In this post, I'll show you how to use PHP's built-in functions to read and print the contents of a CSV file and convert it into an array. We'll use fopen() and fgetcsv() to read the contents of a CSV file, then we'll convert it into an array using the array_map() and str_getcsv() function.

Introduction

Storing data files in comma-separated values (CSV) format is no new thing. In fact, it’s one of the most common ways of storing data due to its simplicity—CSV files are easy to read and write, and can be opened in a basic text editor. This type of file stores tabular data in form of plain text.

An example of such a file would like this:

This data represents information about three people, with columns corresponding to their names, age, and job. Although it's a simple data format, it can be tricky to read and consume it.

Therefore, in this article, I will teach you how to open CSV files using PHP's native functions like fopen(), how to read the contents of this file with the use of the fgetcsv() method, and lastly how to convert this CSV file into an array using the array_map() function.

Of course, there are a number of third-party packages we could use to achieve this, but PHP has built-in native functions that work great. 

Prerequisites

To proceed with this article, you'll need the follwing:

  • PHP version 5.6 or above installed on your machine
  • a development environment for PHP—either XAMPP or WampServer work well
  • some basic understanding of PHP concepts

Let’s begin!

Displaying a CSV File as a Table

In this section of the article, we will be reading a simple CSV file that contains a few words separated by the comma delimiter. For a start, we will use the simple file we used above, then we can later proceed using a random larger file. Of course, you can create your own file using Microsoft Excel or a text editor and save it with the CSV extension.

To read the file, we first have to find it in the folder or location it is saved in. For easier access, you may want to save it in the same folder where you have your program file. Then we can use the fopen() function to read the file.

Afterward, the fgetcsv() function checks for CSV fields from a parsed line of the open file. This function requires three parameters: the file handle returned from fopen(), the maximum length of the line to be read, and the special separator character—which we refer to as the "delimiter". This can either be a comma or a semi-colon or any other separator.

Now let’s get practical.

Create a file named csvtable.php somewhere it can be served with WAMP or XAMPP and copy the following code.

In this file, we're first opening the data.csv file, which should contain some comma-separated data. fopen will look for this file in the same folder as csvtable.php. The 'r' parameter tells fopen to open the file as read-only. 

If the file is opened successfully, fopen will return a file handle which can be used for other file reading operations. Otherwise it will return FALSE. Therefore, we check that the file handle is not FALSE before continuing to read the file.

The fgetcsv() file then fetches CSV fields from the opened file, one line at a time. We tell fgetcsv to read at most 100 characters per line, and to use the comma separator as its delimiter. The words found in the file are then looped through and printed into an HTML table.

The last function is the fclose() function that closes the opened file. This releases the memory used by the open file and allows other processes to have access to the file.

Open csvtable.php through the WAMP or XAMPP localhost server, or run php read.php from the command line to see the following output:

output of read.php fileoutput of read.php fileoutput of read.php file

The first part of what we needed to achieve is done already!

Now, we’ll jump into converting the raw CSV fields into an array.

Converting the Raw CSV File Into an Array

Now, there exists more than one way to produce the array. We can use the fgetcsv() function to automatically convert the contents of the CSV file into an array, or we can use array_map.

Using fgetcsv() to Convert a CSV File Into an Array

This is similar to the example above where we used fgetcsv() to render a CSV file as an HTML table. Let’s see this in action. Create a PHP file with the following contents:

In the above code, we created a function to read a CSV file and convert it to an array. We pass in a parameter with the CSV document file name and path.

Then, we use the feof() function to check whether the end of file has been reached. Until it has, we need to parse the CSV fields using the fgetcsv() function. Just like we did in the example above.

The parsed CSV fields from the CSV file are converted into an array using the fgetcsv() function and are appended one at a time to the $lines[] variable.

Finally, don't forget to use fclose() function to close the opened file before exiting the function.

We then call the readDocument function that passes the csv document as a parameter and next, the contents of the CSV file are displayed as below:

output of csv to array exampleoutput of csv to array exampleoutput of csv to array example

Using array_map() to Read a CSV File

Alternatively, you can use the array_map() function to read a CSV file into an array. To do this, you'll use str_getcsv as a callback function. This is a built-in PHP function that is used to parse a CSV string into an array.

A callback function is an executable code that is passed to another code as an argument. This argument is expected to be called back later on by the code it is passed to.

Here is how we can use array_map and str_getcsv to map our CSV data into an array:

The above code uses the file() method to read the csv file into an array of lines. Then, with array map, it calls str_getcsv() on each line, and store the data for the entire file in $csv. The str_getcsv() function that parses the CSV field contents of each line into an array.

The output of the above code snippet will be the same as above.

Notice how much less code is required when using file() and the the array_map() function directly?

Conclusion

In this article, you learned how to handle a CSV file in PHP by reading and displaying its contents using PHP native functions like fopen() and fgetcsv() and converting the CSV fields into an array. I have showed you two ways to do this. 

Now try doing it yourself. Happy coding!


15 Best Elementor Widgets for WordPress 2022

15 Best Elementor Widgets for WordPress 2022

WordPress is the most popular CMS on the market. Part of what makes WordPress so popular can be attributed to page builder plugins that make it easy to build a website without any coding skills. 

When it comes to page builder plugins, Elementor is one of the most popular page builders out there, occupying 6.7% of the market share. Moreover, Elementor is one of the main reasons why WordPress has seen a growth in popularity, since the use of WordPress without Elementor has actually shrunken. 

The best part about Elementor is that it’s free to download. In addition to that, there are also a ton of third-party widgets for Elementor that extend its capabilities even more. 

Where to Find Elementor Widgets

Elementor Widgets on Envato ElementsElementor Widgets on Envato ElementsElementor Widgets on Envato Elements

If you’re looking for the best Elementor widgets, look no further than Envato Elements. Envato Elements is a premium marketplace that offers thousands of creative assets for all your projects. For a low, monthly fee you get access to hundreds of Elementor widgets as well as:

  • Professional WordPress themes
  • Presentation templates
  • Stock photos, fonts, and more.

Best of all, you can download as many Elementor widgets, templates or WordPress themes as you need and experiment with them until you find the perfect match for your project. Sign up for Envato Elements today and download unlimited creative assets. 

15 Best Elementor Widgets For 2022

Here are some of the best Elementor widgets from Envato Elements that you can use to spice up your website.

1. Elementor Widgets Mega Pack

Elementor Widgets Mega PackElementor Widgets Mega PackElementor Widgets Mega Pack

First up on the list, we have the Elementor Widgets Mega Pack. This pack contains a grand total of 49 widgets and 10 templates for Elementor. You’ll find widgets to display your portfolio, team members, blog post carousels, social shares, WooCommerce widgets, and more.

The template pack also contains 180+ different styles for Elementor so you can easily apply a style that fits your brand. 

2. Image Clipping Mask for Elementor

Image Clipping Mask for ElementorImage Clipping Mask for ElementorImage Clipping Mask for Elementor

Images can do wonders for your website but that doesn’t mean that you have to stick with squares and rectangles all the time. Why not get creative with your images and display them as seals, chat bubbles, arches, and more?

With the help of this widget, you can display your images in creative ways — without having to edit them in a program like Photoshop beforehand. The widget comes with 30+ preset mask images and you can customize everything from colors down to the shape size, border, background, and more.

3. Login Form Widget Elementor Addon Plugin

Login Form Widget Elementor Addon PluginLogin Form Widget Elementor Addon PluginLogin Form Widget Elementor Addon Plugin

Let’s be honest — the default WordPress login form leaves a lot to be desired. But, if you use Elementor, this widget can help you create a completely branded login form for your website. Whether you run a membership site or have contributors, this login form widget is sure to come in handy.

The widget comes in 2 layout styles. You can customize how the fields look, change the fonts, set redirect URLs, control where the widget shows up, and more.

4. Video Clipping Mask for Elementor

Video Clipping Mask for ElementorVideo Clipping Mask for ElementorVideo Clipping Mask for Elementor

If you want people to connect with you, it’s a good idea to incorporate video into your site. However, most websites stick to the traditional video presentation that comes with the platform embed codes. Why not make your videos pop with the help of a video clipping mask widget for Elementor?

Similarly to the Image Clipping Mask widget, this Elementor widget allows you to display your videos in creative ways. The widget comes with 40+ preset masks as well as five templates. It’s fully customizable and supports Youtube, Vimeo, and other internal and external video sources.

5. Animated Heading for Elementor

Animated Heading for ElementorAnimated Heading for ElementorAnimated Heading for Elementor

Use this Elementor widget to instantly transform your post and page titles. The widget is perfect for any website that wants to stand out from the rest. When you download and install the widget, you’ll get 5 premade animated templates as well as 16 animation styles that you can apply to your headings. The widget is also fully customizable. You can change colors, fonts, background, rotate the header, and more. It’s a flexible widget that’s sure to grab your visitors’ attention.

6. Timeline for Elementor

Timeline for ElementorTimeline for ElementorTimeline for Elementor

Next, we have a timeline widget for Elementor. This type of widget comes in handy for many different website types. For example, if you’re creating a resume website, you can use the timeline widget to showcase your education as well as past experience. If you’re building a business website, you can use the timeline to display your company history.

This widget comes in horizontal and vertical style and it’s fully responsive. It’s easy to customize. You have full control over how many elements are visible as well as how the timeline itself looks.

7. Elementor Post Grid, List, Carousel Slider

Blogging is one of the best ways to promote your business, grow your organic traffic, and improve your SEO. With the help of this widget, you’ll be able to style your blog posts and display them in a visually appealing way.

Elementor Post Grid, List, Carousel SliderElementor Post Grid, List, Carousel SliderElementor Post Grid, List, Carousel Slider

The widget allows you to control how many posts display per page and you can even select to display only posts from a certain category. In other words, you have plenty of options to configure how the posts should look on your page. On top of that, you can also customize fonts, colors, spacing, and other visual settings.

8. WooCommerce Mini Cart Widget for Elementor

WooCommerce Mini CartWooCommerce Mini CartWooCommerce Mini Cart

Boost your store sales with the help of this mini cart widget for Elementor. It allows you to enhance the checkout experience in your store by adding a mini cart in your website’s header. Once the visitor clicks the header, they can see which items they have in the cart and immediately proceed to the checkout page. 

9. Slideshow & Slider for Elementor

Slideshow and Slider for ElementorSlideshow and Slider for ElementorSlideshow and Slider for Elementor

Here’s another useful widget for Elementor that you can use to display all kinds of information. The Slideshow & Slider widget for Elementor comes with 6 premade templates that you can use to showcase past projects, team members, testimonials, and more.

You can customize the height of the slider as well as how the slider looks. Everything from colors down to the font is completely customizable so you can make it match the rest of your site. The widget is responsive so you can rest assured your slideshow will look good on both desktop and mobile devices. Plus, it has support for touch and swipe navigation.

10. Pricing Table addon - widget for Elementor

Pricing Table AddonPricing Table AddonPricing Table Addon

Even if you don’t sell products, it’s still important to display prices on your site. With the Pricing Table widget for Elementor, you’ll be able to present prices for your service or consulting packages in a stylish fashion. You can choose between 9 different styles as well as customize them to your liking to ensure your pricing tables match the rest of your site. The widget is fully responsive.

11. Team Member addon - widget for Elementor

Team Member AddonTeam Member AddonTeam Member Addon

This widget is the perfect choice if you want to showcase members on your team or key employees. It’s also handy if you have multiple instructors and want potential visitors to be able to choose which employee or team member they’d like to work on.

The widget allows you to customize the appearance. You have the option to enter a short description as well as add links to their social media profiles. The widget is fully responsive so you can rest assured it will look good no matter which device your visitors are using. 

12. Before After Image Slider Elementor Addon

Before After Image SliderBefore After Image SliderBefore After Image Slider

One of the best ways to build trust with potential clients is to show the results you get for clients. This is particularly true if you provide a personal service or work in a creative industry. That’s where this Before After Image Slider widget for Elementor comes in. You can show the differences between two images to clearly show the transformation. For example, if you offer home remodeling services, this widget can show what the home looked like before and after.

The widget is responsive and easy to customize. You can also choose between a horizontal or vertical layout. 

13. Countdown Timer Elementor Page Builder Addon

Countdown Timer for ElementorCountdown Timer for ElementorCountdown Timer for Elementor

The countdown timer widget is a great choice if you want to showcase limited offers or get people excited for an event, a promotion, or a special occasion. You can customize every aspect of the widget and configure various settings. For example, you can easily set what happens once the timer runs out: whether you want to display custom content or redirect visitors to a different page. The widget is fully responsive.

14. Graphs & Charts for Elementor

Graphs and Charts for ElementorGraphs and Charts for ElementorGraphs and Charts for Elementor

Consider this widget if you need to display a lot of different data on your website. This widget allows you to display line charts, pie charts, bi-polar line charts, donut charts, and more. In total, it offers 12 different types of charts and they’re each customizable so you can configure the charts to your liking. The widget is also fully responsive so it will look good no matter which device your visitors are using.

15. WooCommerce Elementor Addons

WooCommerce Elementor AddonWooCommerce Elementor AddonWooCommerce Elementor Addon

Elevate your online store with this set of WooCommerce addons for Elementor. This particular plugin makes it easy to display your products in a variety of ways. You can choose between grid, carousel, pagination, and load more layout.

You can configure the number of products to be shown, set it to show featured products, best-selling products, products on sale, and more. This also includes the ability to enable product quick view as well as product comparison. All of the widgets are customizable and responsive. 

Learn More About Elementor

Elementor is a powerful page builder plugin for WordPress that can be a little overwhelming for new users. Luckily, we have plenty of tutorials to help you learn more about working with Elementor. Get started with the tutorials below: 

Discover More Elementor Resources

Elementor widgets are not the only resources available for Elementor. There are also numerous Elementor themes and templates built specifically for Elementor. As mentioned earlier, Envato Elements is the best marketplace to find those Elementor resources. If you’re looking for more Elementor templates, be sure to check out the roundups below: 

Level Up Your Website With Elementor Widgets

Elementor is a powerful and popular page builder plugin that makes it easy to build a website without any coding skills. While Elementor offers a lot of the features out of the box, there are plenty of Elementor widgets that you can install to add even more features to your website. 

If you’re looking for premium Elementor widgets, stop by Envato Elements. We have hundreds of unique Elementor widgets as well as thousands of other creative assets that will help you take your website to the next level.