skip to Main Content

I have a text file. I want to read the file and get some of datas from the element. While i read this file it may be return string (I am not sure).The file contains some data which like the follwing :

Can we get Prism Cluster Mail in summarize way like below.  
----------------------------------------------------------------

{
   "Employees":[
      {
         "userId":"rirani",
         "jobTitleName":"Developer",
         "firstName":"Romin",
         "lastName":"Irani",
         "preferredFullName":"Romin Irani",
         "employeeCode":"E1",
         "region":"CA",
         "phoneNumber":"408-1234567",
         "emailAddress":"[email protected]"
      },
      {
         "userId":"nirani",
         "jobTitleName":"Developer",
         "firstName":"Neil",
         "lastName":"Irani",
         "preferredFullName":"Neil Irani",
         "employeeCode":"E2",
         "region":"CA",
         "phoneNumber":"408-1111111",
         "emailAddress":"[email protected]"
      },
      {
         "userId":"thanks",
         "jobTitleName":"Program Directory",
         "firstName":"Tom",
         "lastName":"Hanks",
         "preferredFullName":"Tom Hanks",
         "employeeCode":"E3",
         "region":"CA",
         "phoneNumber":"408-2222222",
         "emailAddress":"[email protected]"
      }
   ]
}

Best Regards
The Team

I want to extract userId,jobTitleName and phoneNumber. How can i do this? I am a new in php. I have tried by the folowing code. But it does not work properly. Can anyone please help ?

header('Content-type: application/json');   
    $data = preg_split("/rn/", file_get_contents("cluster.txt")); 
    $dt= json_encode($data, JSON_UNESCAPED_SLASHES);
    $final_dt=stripslashes($dt);
    $final_dt_arr=json_decode($final_dt,true);
    //echo "<pre>"; print_r($final_dt_arr);
    echo $final_dt;

4

Answers


  1. I take a look on your script above, you already used json_decode, this is a good start.
    Can you please try the code below (most of my projects) use it:

    // Read the JSON file into a string
    $json_string = file_get_contents('urjsonfile.json');
    
    // Decode the JSON string into a PHP object
    $data = json_decode($json_string);
    
    // Extract the desired data from the object
    foreach ($data->Employees as $employee) {
        $userId = $employee->userId;
        $jobTitleName = $employee->jobTitleName;
        $phoneNumber = $employee->phoneNumber;
    
        // Do something with the extracted data, such as print it out
        echo "User ID: $userId, Job Title: $jobTitleName, Phone Number: $phoneNumbern";
    }
    
    1. file_get_contents() function reads the JSON file into a string
    2. decoded using json_decode() into a PHP object
    3. foreach loop then iterates over each element of the Employees array in the object, extracting the desired data.

    you can also pass the second argument as true to return an associative array instead.

    Login or Signup to reply.
  2. @Lia, First you will pick only json data from your string, then you will convert to array. here goes your code.

    $str_data = file_get_contents("cluster.txt"); 
            if (strpos($str_data, '{') !== false) {
                $str_data = str_split($str_data);
                // extract the json message.
                $json = '';
                $in = 0;
                foreach ($str_data as $i => $char) {
                    if ($char == '{') {
                        $in++;
                    }
                    if ($in) {
                        $json .= $str_data[$i];
                    }
                    if ($char == '}') {
                        $in--;
                    }
                }
                if ($json) {
                    $json = json_decode($json);
                }
                
                $array = json_decode(json_encode($json), true);
                echo "<pre>"; print_r($array);
                // now chill with your array
            }
    
    Login or Signup to reply.
  3. If the file will always have exactly 3 lines of non-JSON content at the beginning and end, you can just remove that extraneous content from the data before trying to decode it, and then resume decoding and using the JSON data in the usual way.

    For example:

    $file_data = file_get_contents("cluster.txt"); 
    
    //get file data into an array and remove first 3 lines
    $file_data_arr = explode("n", $file_data);
    $file_data_arr = array_slice($file_data_arr, 3);
    
    //Now remove last 3 lines and convert back to a string
    array_splice($file_data_arr, -3);
    $json_string = implode("n", $file_data_arr);
    
    // Decode the JSON string into a PHP object
    $data = json_decode($json_string);
    
    // Extract the desired data from the object
    foreach ($data->Employees as $employee) {
        $userId = $employee->userId;
        $jobTitleName = $employee->jobTitleName;
        $phoneNumber = $employee->phoneNumber;
    
        // Do something with the extracted data, such as print it out
        echo "User ID: $userId, Job Title: $jobTitleName, Phone Number: $phoneNumbern";
    }
    

    Working demo: https://3v4l.org/Ar7ne

    Login or Signup to reply.
  4. Well, as I saw all the comments about this crapy file content with text and JSON mixed together, I think the only thing you could do is to try to extract only the JSON part of the file which is between the opening and closing braces ({}).

    This could be done with the help of a regular expression. It’s clearly not very safe because the surrounding text could also have those chars. We’ll say it’s not the case…

    The simple regular expression would be /{.*}/s

    But we can improve it a bit, as we know that it should contain
    the Employees entry. This can help if the rest of the file also
    has some braces in the comments. The regex would become:

    /{s*"Employees"s*:s*[.*]s*}/su
    

    Regular expression visualization

    To test it with crapy content and have the explanation of the pattern: https://regex101.com/r/wPGwIk/1

    The full PHP code:

    <?php
    
    // $input_data = file_get_contents('cluster.txt');
    
    // The crapy file content with the JSON inside it.
    $input_data = <<<END_OF_FILE
    Can we get Prism Cluster Mail in summarize way like below. {dummy}
    ----------------------------------------------------------------
    
    {
       "Employees":[
          {
             "userId":"rirani",
             "jobTitleName":"Developer",
             "firstName":"Romin",
             "lastName":"Irani",
             "preferredFullName":"Romin Irani",
             "employeeCode":"E1",
             "region":"CA",
             "phoneNumber":"408-1234567",
             "emailAddress":"[email protected]"
          },
          {
             "userId":"nirani",
             "jobTitleName":"Developer",
             "firstName":"Neil",
             "lastName":"Irani",
             "preferredFullName":"Neil Irani",
             "employeeCode":"E2",
             "region":"CA",
             "phoneNumber":"408-1111111",
             "emailAddress":"[email protected]"
          },
          {
             "userId":"thanks",
             "jobTitleName":"Program Directory",
             "firstName":"Tom",
             "lastName":"Hanks",
             "preferredFullName":"Tom Hanks",
             "employeeCode":"E3",
             "region":"CA",
             "phoneNumber":"408-2222222",
             "emailAddress":"[email protected]"
          }
       ]
    }
    
    Best Regards
    ~{ The Team }~
    END_OF_FILE;
    
    
    // Extract the JSON which should have the "Employees" entry.
    if (preg_match('/{s*"Employees"s*:s*[.*]s*}/su', $input_data, $matches)) {
        $data = json_decode($matches[0]);
        
        if ($error = json_last_error()) {
            print "Could not decode the JSON string!n";
            exit(2);
        }
        
        print "userIdtjobTitleNametphoneNumbern";
        print "-----------------------------------n";
        foreach ($data->Employees as $id => $employee) {
            print "$employee->userIdt$employee->jobTitleNamet$employee->phoneNumbern";
        }
    }
    else {
        print "No JSON found!n";
        exit(1);
    }
    

    Execution output:

    userId  jobTitleName    phoneNumber
    -----------------------------------
    rirani  Developer   408-1234567
    nirani  Developer   408-1111111
    thanks  Program Directory   408-2222222
    

    You can run it here: https://onlinephp.io/c/5386c

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search