0

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":"romin.k.irani@gmail.com"
      },
      {
         "userId":"nirani",
         "jobTitleName":"Developer",
         "firstName":"Neil",
         "lastName":"Irani",
         "preferredFullName":"Neil Irani",
         "employeeCode":"E2",
         "region":"CA",
         "phoneNumber":"408-1111111",
         "emailAddress":"neilrirani@gmail.com"
      },
      {
         "userId":"thanks",
         "jobTitleName":"Program Directory",
         "firstName":"Tom",
         "lastName":"Hanks",
         "preferredFullName":"Tom Hanks",
         "employeeCode":"E3",
         "region":"CA",
         "phoneNumber":"408-2222222",
         "emailAddress":"tomhanks@gmail.com"
      }
   ]
}

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("/\r\n/", 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;
Lia Barua
  • 1
  • 2
  • 2
    I don't see what your attempt is supposed to have to do with the question of extracting data in the first place? Why are you hacking this apart into individual lines, that you then JSON-encode and decode again? – CBroe Feb 21 '23 at 13:34
  • Please carefully read the accepted answer at [How to extract and access data from JSON with PHP?](https://stackoverflow.com/questions/29308898/how-to-extract-and-access-data-from-json-with-php) and then apply the concepts you've learned into your attempt to get data from your own JSON – ADyson Feb 21 '23 at 13:34
  • 2
    Just to be clear - the text _"Can we get ..."_ and the following `----` line are actually part of your file content, yes? Then you should split those of, and then decode the rest as the valid JSON it is. – CBroe Feb 21 '23 at 13:35
  • Actually I am totally new in php and dont know how I do this? – Lia Barua Feb 21 '23 at 13:38
  • 1
    That's why I gave you a guide to learn the principles from! Make sure you understand about PHP arrays in general as well. If you learn the principles, then you can apply them, and then you can solve this scenario and all related scenarios in future. – ADyson Feb 21 '23 at 13:39

4 Answers4

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: $phoneNumber\n";
}
  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.

da_root
  • 364
  • 2
  • 11
  • **Comments have been [moved to chat](https://chat.stackoverflow.com/rooms/252052/discussion-on-answer-by-da-root-read-a-text-file-and-extract-some-of-element-in); please do not continue the discussion here.** Before posting a comment below this one, please review the [purposes of comments](/help/privileges/comment). Comments that do not request clarification or suggest improvements usually belong as an [answer](/help/how-to-answer), on [meta], or in [chat]. Comments continuing discussion may be removed. – Machavity Feb 22 '23 at 15:39
0

@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
        }
S Sopno
  • 19
  • 3
0

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: $phoneNumber\n";
}

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

ADyson
  • 57,178
  • 14
  • 51
  • 63
0

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":"romin.k.irani@gmail.com"
      },
      {
         "userId":"nirani",
         "jobTitleName":"Developer",
         "firstName":"Neil",
         "lastName":"Irani",
         "preferredFullName":"Neil Irani",
         "employeeCode":"E2",
         "region":"CA",
         "phoneNumber":"408-1111111",
         "emailAddress":"neilrirani@gmail.com"
      },
      {
         "userId":"thanks",
         "jobTitleName":"Program Directory",
         "firstName":"Tom",
         "lastName":"Hanks",
         "preferredFullName":"Tom Hanks",
         "employeeCode":"E3",
         "region":"CA",
         "phoneNumber":"408-2222222",
         "emailAddress":"tomhanks@gmail.com"
      }
   ]
}

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 "userId\tjobTitleName\tphoneNumber\n";
    print "-----------------------------------\n";
    foreach ($data->Employees as $id => $employee) {
        print "$employee->userId\t$employee->jobTitleName\t$employee->phoneNumber\n";
    }
}
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

Patrick Janser
  • 3,318
  • 1
  • 16
  • 18