-11

I have some contents from a text file. I want to load it into a variable in PHP

I just need to copy/paste the text directly into a variable without escaping all quotes etc

How to do something like this? I'm not looking for a solution with file_get_content, since my use case's environment does not support file reads.

$str = "saldflasdfl

asdklksadlasd "quoted string"


aslkdlsadfkl";
halfer
  • 19,824
  • 17
  • 99
  • 186
clarkk
  • 27,151
  • 72
  • 200
  • 340
  • [chat link](http://chat.stackoverflow.com/transcript/message/34277177#34277177) for close reason change – Drew Nov 26 '16 at 19:53

3 Answers3

1

How about this, which allows you to use unescaped quote marks in your text block:

$str = <<<DATA
saldflasdfl

asdklksadlasd "quoted string"


aslkdlsadfkl
DATA;

Note that it does need to be added with no whitespace indentation, since that would be taken to be part of the string.

However, do note that if your text block gets over a certain size, it is probably cleaner to put it in a text file and read it into a string.

halfer
  • 19,824
  • 17
  • 99
  • 186
0

You need to escape ":

$str = "saldflasdfl

asdklksadlasd \"quoted string\"


aslkdlsadfkl";
nospor
  • 4,190
  • 1
  • 16
  • 25
  • I need to copy the text directly.. I dont want to read 292838 lines of text and escape all quotes – clarkk Jun 02 '16 at 11:18
  • So use your editor to replace all " into \" – nospor Jun 02 '16 at 11:23
  • If it really is that many lines of text I would have thought you'd want to put them in a text file and load them into the variable, rather than dumping it all directly into the PHP file. – Octopoid Jun 02 '16 at 11:26
0

This code reads the whole file.

$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
$str =  fread($myfile,filesize("webdictionary.txt"));
fclose($myfile);

If you wanna read one line at a time you can do this:

$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
// Output one line until end-of-file
while(!feof($myfile)) {
  echo fgets($myfile) . "<br>";
}
fclose($myfile);

Source: http://www.w3schools.com/php/php_file_open.asp

patricia
  • 1,075
  • 1
  • 16
  • 44
  • I not looking for at solution which read a file – clarkk Jun 02 '16 at 11:19
  • @clarkk can you explain it better in your question then? What do you have and what do you want do have? "I have some contents from a text file.. I want to load it into a variable in PHP" this seem like you wanna read something from a file and load it into a variable (that's what I answered. So tell me what do you really want so I can help you. – patricia Jun 02 '16 at 11:21