Priya Vaidyanathan
Priya Vaidyanathan

Reputation: 13

How to use 2 delimitters while reading from a file in PHP

I'm trying to create an online quiz web app and Im stuck with reading from the files that have the questions.enter code here. This is the file :

@$!#include<stdio.h>
void main()
{
printf();
scanf();
}
@$!#include<stdio.h>
void main()
{  
printf();
scanf();
}
@$!#include<stdio.h>
void main()
{
printf();
scanf();
}

SO i have to read from @$! to the next @$! while also the new line sequence should be maintained. MY php code looks like this

<?php
$filename = "newfile.txt";
$fd = fopen ($filename, "r");
$contents = fread ($fd,filesize ($filename));
fclose ($fd); 
$delimiter = "\n";
$splits= explode($delimiter, $contents);
foreach ( $splits as $show )
{

$ctr = explode("@$!",$show);
foreach($ctr as $nl)
echo $nl;

} 


 ?>

The output looks like this:

   #include void main() { printf(); scanf(); } #include void main() {   
   scanf(); } #include void main() { printf(); scanf(); } 

all in one straight line. Anything Am i missing? Or is there another way to do it?

Upvotes: 1

Views: 30

Answers (1)

Maulik Kanani
Maulik Kanani

Reputation: 652

<?php
$filename = "update.txt";
$contents =  nl2br(file_get_contents($filename));
?>

Would you please use this to read file ?

Result:

@$!#include
void main()
{
printf();
scanf();
}
@$!#include
void main()
{
printf();
scanf();
}
@$!#include
void main()
{
printf();
scanf();
} 

Your modified code:

<?php
$filename = "newfile.txt";
$contents =  nl2br(file_get_contents($filename));
$delimiter = "\n";
$splits= explode($delimiter, $contents);
foreach ( $splits as $show )
{

$ctr = explode("@$!",$show);
foreach($ctr as $nl)
echo $nl;

} 
?>

Result:

#include
void main()
{
printf();
scanf();
}
#include
void main()
{
printf();
scanf();
}
#include
void main()
{
printf();
scanf();
}

Upvotes: 2

Related Questions