-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdata.php
More file actions
69 lines (48 loc) · 1.3 KB
/
Copy pathdata.php
File metadata and controls
69 lines (48 loc) · 1.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
<?php
function writeObjectsToFile($filename, $objects)
{
$file = fopen($filename, 'a');
if ($file === false) {
die("Unable to open the file.");
}
foreach ($objects as $object) {
fwrite($file, json_encode($object) . PHP_EOL);
}
fclose($file);
}
function readObjectsFromFile($filename)
{
$file = fopen($filename, 'r');
if ($file === false) {
die("Unable to open the file.");
}
$objects = [];
while (($line = fgets($file)) !== false) {
$objects[] = $line;
}
fclose($file);
return $objects;
}
function searchAndReplaceObject($filename, $searchWord, $newObject)
{
$lines = file($filename);
$newObjectJson = json_encode($newObject);
foreach ($lines as $key => $line) {
if (strpos($line, $searchWord) !== false) {
$lines[$key] = $newObjectJson . PHP_EOL;
}
}
file_put_contents($filename, $lines);
}
$objects = [
['name' => 'John', 'age' => 25],
['name' => 'Sara', 'age' => 23],
];
$filename = 'data.dnof';
writeObjectsToFile($filename, $objects);
print_r(readObjectsFromFile($filename));
$searchWord = 'John';
$newObject = ['name' => 'John', 'age' => 26];
searchAndReplaceObject($filename, $searchWord, $newObject);
print_r(readObjectsFromFile($filename));
?>