Skip to content
Advertisement

How to separate the full name that has comma in excel using php

I have a project that gets the name from excel and stores the value in the first name and last name. The problem is that in the excel file the name is stored (for example John, Constantine) how do I get the John and Constantine and store it in two different variables?

if(isset($_POST['excel_btn']))
{
    require('import/PHPExcel/PHPExcel.php');
    require('import/PHPExcel/PHPExcel/IOFactory.php');

    $file=$_FILES['myFile']['tmp_name'];
    

    $obj=PHPExcel_IOFactory::load($file);
    foreach($obj->getWorksheetIterator() as $sheet)
    {
        $getHighestRow=$sheet->getHighestRow();
        for($i=1; $i<=$getHighestRow; $i++){
            $name=$sheet->getCellByColumnAndRow(0,$i)->getValue();
           
             if($name !=''){
                 $query = "INSERT INTO users(name) VALUES('$name')";
            
            $query_run=mysqli_query($conn, $query);

            }
    }
}

this is what I wrote so far but with that, the full name is stored in the variable $name

Advertisement

Answer

(Updated)

Use explode :

$pieces = explode(",", $name);
echo trim($pieces[0]); // John
echo trim($pieces[1]); // Constantine

Or, as @Markus Zeller:

list($first, $last) = explode(',', 'John, Constantine')
echo trim($first);
echo trim($last);
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement