Inside this article we will see the concept i.e How To Get File Name From a Path in PHP Example. Article contains the classified information about PHP basename() and pathinfo() functions.
Sometimes when you work, you need the filename from any specific path. So, this tutorial will be helpful for you for this. Tutorial is super easy to understand and implement it in your code as well.
Let’s get started.
Create a folder say path-filename in your localhost directory. Create a file index.php into it.
We have several methods to get the filename from a file path. Here, we will see two standard methods to get in very easier way.
Method #1: Using basename() PHP function
<?php $path = "S:/projects/mysample-app/data.xml"; $file = basename($path).PHP_EOL; print_r($file); // Output: data.xml echo "<br/>"; $file = basename($path, ".xml"); print_r($file); // Ouput: data
Method #2: Using pathinfo() PHP function
<?php $path = "S:/projects/mysample-app/data.xml"; echo pathinfo($path, PATHINFO_BASENAME) . PHP_EOL; // Output: data.xml echo "<br/>" echo pathinfo($path, PATHINFO_FILENAME); //Output: data echo "<br/>"; print_r(pathinfo($path));
data.xml data Array ( [dirname] => S:/projects/mysample-app [basename] => data.xml [extension] => xml [filename] => data )
We hope this article helped you to learn How To Get File Name From a Path in PHP Example in a very detailed way.
Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.