In PHP how to sort a file in reverse? - php

i have a text (text.txt) file like this:
shir
beer
geer
deer
i have also a php page with that source:
<?php
foreach (glob("*.txt") as $filename) {
$file = $filename;
$contents = file($file);
$reverse = array_reverse($file, true);
$string = implode("<br>" , $contents);
echo $string;
echo "<br></br>";
}
?>
I want that in the php page it will show:
deer
geer
beer
shir
from the end of the file to the beginning.
thank you

Looks like you are reversing the file name and not the contents.
Do
$reverse = array_reverse($content); // you can drop 2nd arg.
$string = implode("<br>" , $reverse);
in place of
$reverse = array_reverse($file, true);
$string = implode("<br>" , $contents);
Also you can remove the temp variables from you script and do:
foreach (glob("*.txt") as $filename) {
echo implode("<br>" , array_reverse(file($filename))) . "<br></br>";
}

<?php
foreach (glob("*.txt") as $filename) {
$file = $filename;
$contents = file($file);
$reverse = array_reverse($contents, true);
$string = implode("<br>" , $reverse);
echo $string;
echo "<br></br>";
}
?>
Your result was a $contents, without reverse.

Related

read json file line by line

i want to read test.txt file line by line that i converted it to object but my problem is it just read line 1 and something is wrong because loading is little long
$file = fopen(__DIR__.'/test.txt','r');
while (!feof($file)){
$file = fgets($file);
$obj = json_decode($file);
echo $obj->sid;
echo "<hr>";
}
this my test.txt:
{"sid":5555,"trans-id":"PROV_149663920543900000801","status":"0","base-price-point":"0","msisdn":"989905978846","keyword":"sub1","validity":1}
{"sid":2244,"trans-id":"PROV_149663920543900000801","status":"0","base-price-point":"0","msisdn":"989905978846","keyword":"sub1","validity":1}
You are overwriting $file on line 3 of your code. Change it to $line and you are good to go.
$file = fopen(__DIR__.'/test.txt','r');
while (!feof($file)){
$line = fgets($file);
$obj = json_decode($line);
echo $obj->sid;
echo "<hr>";
}
Try this:
<?php
$filename= __DIR__.'/test.txt';
$array = explode("\n", file_get_contents($filename));
foreach ( $array as $line)
{
$obj = json_decode($line);
echo $obj->sid;
echo "<hr>";
}
?>
Use the file() function:
$contents = file(__DIR__.'/test.txt');
foreach ($contents as $line)
{
$obj = json_decode($line);
echo $obj->sid;
echo "<hr>";
}
The file() function read a file and create an array with each line of the file's contents.
I'd suggest using file to read the file as this generates the individual lines as array entries so you can iterate though each line using a foreach
$file=__DIR__ . '/json_src.txt';
$lines=file($file);
foreach( $lines as $line ){
$json=json_decode( $line );
printf('%s<hr />', $json->sid );
}

Read Files from directory and echo certain line

I want to read all files from a directory but instead of displaying the first character i want to display a certain line, f.e. line 4.
<?php
$directory = "content/";
$dir = opendir($directory);
while (($file = readdir($dir)) !== false) {
$filename = $directory . $file;
$type = filetype($filename);
if ($type == 'file') {
$contents = file_get_contents($filename);
$items = explode("|", $contents);
foreach ($items as $item) {
echo "$item[0]";
}
}
}
closedir($dir);
?>
Thanks!
You can use file() function. It reads files into an array, where every line will be an array member, to skip empty lines pass the FILE_SKIP_EMPTY_LINES flag paramater.
For more info consult the docs.
// `$items` is already an array
$items = explode("|", $contents);
// if you want first element of array just:
echo $item[0];
// if you want fourth element of array just:
echo $item[3];
// without `foreach`
Could you show your file structure, please?
Basicaly you can use something like this:
$contents = file_get_contents($filename);
$items = explode("\r\n", $contents); //explode file content
foreach ($items as $item) {
echo $item[3]; //echo your line
}

Replacing a word in an output. php

<?php
$file = 'C:\wamp\www\Killboard\EPChernarus1\PhitLog.txt';
$searchfor = 'Chernarus';
header('Content-Type: text/html');
$contents = file_get_contents($file);
$contents = str_replace("(ArmA-AH.net)", "(DayZNorway.com)", $contents);
$pattern = preg_quote($searchfor, '/');
$contents = str_replace("DayZ Instance: 11", " Map: Chernarus ", $contents);
$pattern = "/^.*$pattern.*$/m";
$contents = str_replace("PKILL", "Player Killed", $contents);
$contents = str_replace("CLOG", "Combat Logged", $contents);
if(preg_match_all($pattern, $contents, $matches)){
echo "<strong>";
echo "<div style ='font:11px/21px Arial,tahoma,sans-serif;color:#2983CB'>Killboard Epoch Chernarus: <br>";
echo '', implode(" <br>", $matches[0]);
echo "</strong>";
}
else
{
echo "No kills yet. Looks like everyone is playing nice.";
}
?>
After much help on here, code now looks this ^
Now i am trying to include the code below.
So that it will rename the weapon classes to more userfriendly names.
I have included the two .php files its looking for, but i am unsure to where i place it and if it will even run like it is, wich i doubt.
Could someone
if ($line_type == 'kill') {
include("killfeed_weapon_classnames.php");
include("killfeed_weapon_cleannames.php");
$swap_key = array_search($line_varlist['weapon'], $wcn);
if($swap_key != false) { $line_varlist['weapon'] = $wn[$swap_key]; }
}
Before all of your preg matching and right after $contents use:
$contents = str_replace("(Arma-AH.net)", "(DayZNorway.com)", $contents);
Edited forgot the parenthesis and next question. I am not going to just give you the next part, but look at the example below and follow along this should help you achieve what you want for that next question.
$myArray = array("firstName" =>"sam", "secondName" => "billy", "thirdName" => "sally");
$nameKey = array_search("billy", $myArray);
echo $nameKey;
if($nameKey){
$myArray[$nameKey] = "Tom";
}
print_r($myArray);
<?php
$file = 'C:\wamp\www\Killboard\EPChernarus1\PhitLog.txt';
$searchfor = 'Chernarus';
header('Content-Type: text/html');
$contents = file_get_contents($file);
$contents = str_replace("(ArmA-AH.net)", "(DayZNorway.com)", $contents);
$pattern = preg_quote($searchfor, '/');
$contents = str_replace("DayZ Instance: 11", " Map: Chernarus ", $contents);
$pattern = "/^.*$pattern.*$/m";
$contents = str_replace("PKILL", "Player Killed", $contents);
$contents = str_replace("CLOG", "Combat Logged", $contents);
if(preg_match_all($pattern, $contents, $matches)){
echo "<strong>";
echo "<div style ='font:11px/21px Arial,tahoma,sans-serif;color:#2983CB'>Killboard Epoch Chernarus: <br>";
echo '', implode(" <br>", $matches[0]);
echo "</strong>";
}
else
{
echo "No kills yet. Looks like everyone is playing nice.";
}
?>
This is what i ended up doing, now its hardly pretty, but it works.
Now i need to get the results to show in descending order.
Any chance someone could help me with this?

How can i show all lines of a text document except a specific line in PHP?

$file=fopen("question.txt","r");
while(!feof($file))
{
echo "<h3>". fgets($file)."</h3>"."<br />";
for($i=0;$i<=3;$i++)
{
echo fgets($file)."<br />";
}
}
$lines =file("filename.txt");
and then $lines[4] will return you fifth line.
Find and replace the line. Look at str_replace function at http://php.net/manual/en/function.str-replace.php :)
Maybe a better option in this case... Use the file($path) function to get the lines into an array, then loop through it.
$lines = file($path, FILE_IGNORE_NEW_LINES);
$remove = "balblalbllablab";
foreach($lines as $key => $line)
if(stristr($line, $remove)) unset($lines[$key]);
$data = implode('\n', array_values($lines));
$file = fopen($path);
fwrite($file, $data);
fclose($file);

How to Remove Duplicate Domains from a Large List of URLs

I want To remove duplicate domains in the list of URL ,For example Below is the text file
http://www.exampleurl.com/something.php
http://www.domain.com/something.php
http://www.exampleurl.com/something111.php
http://www.exampleurl.com/something111.php
http://www.exampleurl.com/something222.php
I need to remove duplicate domain and i need below list
http://www.exampleurl.com/something.php
http://www.domain.com/something.php
Below is the code that just remove duplicates in an text file.
$text = array_unique(file($filename));
$f = #fopen("promo1.txt",'w+');
if ($f) {
fputs($f, join('',$text));
fclose($f);
}
?>
Can anyone help me ?
$urls = file('domains.txt');
$uniqueDomains = array_reduce (
$urls,
function (array $list, $url) {
$domain = parse_url($domain, PHP_URL_HOST);
if (!isset($list[$domain])) $list[$domain] = $url;
return $list;
},
array()
);
$uniqueDomains has the hostname as key. If you don't need (and/or want) it use array_values($uniqueDomains);
To compare on the domains, you can use parse_url:
<?php
$text = file_get_contents("input.txt");
$lines = explode("\n",$text);
$filtered_domains = array();
foreach($lines as $line)
{
$parsed_url = parse_url($line);
if(array_search($parsed_url['host'], $filtered_domains) === false)
{
$filtered_domains[$line] = $parsed_url['host'];
}
}
$output = implode("\n", array_keys($filtered_domains));
file_put_contents("output.txt", $output);
?>
<?php
/*
$lines = file('textfile.txt');
*/
$lines = array(
'http://www.exampleurl.com/something.php',
'http://www.domain.com/something.php',
'http://www.exampleurl.com/something111.php',
'http://www.exampleurl.com/something111.php',
'http://www.exampleurl.com/something222.php'
);
foreach($lines as $line){
$url_parsed = parse_url($line);
if(is_array($url_parsed)){
$host = $url_parsed['host'];
if(!#$uniques[$host]){
$uniques[$host] = $line;
}
}
}
echo join('',$uniques);
$f = #fopen("promo1.txt",'w+');
if ($f) {
fputs($f, join("\n",$uniques));
fclose($f);
}
?>
To remove duplicates from an array you can use array_unique(). To make your list an array you can use explode(). Then to make it a string again you can use implode().
To put this all together you can use the following code:
$list = "http://www.exampleurl.com/something.php
http://www.domain.com/something.php
http://www.exampleurl.com/something111.php
http://www.exampleurl.com/something111.php
http://www.exampleurl.com/something222.php";
$newList = implode("\n", array_unique(explode("\n", $list)));

Categories