Cannot output a big string block without break lines (nginx+php) - php

I try to print a big JSON block (100k) to the browser, but the server fails without an error.
For example:
echo 'var config = ' . json_encode( $config ) . ';' . PHP_EOL;
I Have found that if i send a small piece, it's OK.
I have found that if I put line breaks in the JSON string, it's OK even if the string is 400k.
For example:
$config_json = json_encode( $config );
$config_json = str_replace( '},', '},' . PHP_EOL, $config_json );
echo 'var config = ' . $config_json . ';' . PHP_EOL;
But the breaklines breaks my JSON.
So, if it's a buffer setting, why the PHP_EOL helps?
I have tried also to split the JSON to pieces like here: https://stackoverflow.com/a/19156563/1009525, But without success, Only the breaklines helps me.

As you write
the server fails without an error
I presume you mean that the server sends a response to the client (status code: 200 - no error), but the response body (the content) is empty (this is the failure).
You should check this because if actually the server sends a response with content then the issue is not with php, nginx or buffering.
Otherwise (as suggested in comments) maybe the JSON instead of inside a <script> - </script> block may be wrapped between <pre> tags and this could be the problem (but I can't help unless you post more of your code).
From now on I assume the response sent from the server is empty
The code you posted is valid and is supposed to handle correctly the output string you're building up (that's far below PHP limits).
Said that it seems a weird buffering issue. I write "weird" because as far as I know (and I took time to do some research too) buffering should not be influenced by line breaks.
I have found that if I put line breaks in the JSON string, it's OK even if the string is 400k.
A quick workaround to solve your problem is to output a valid JSON with line breaks. You just need to specify an option to json_encode:
echo 'var config = ' . json_encode( $config, JSON_PRETTY_PRINT ) . ';' . PHP_EOL;
JSON_PRETTY_PRINT tells json_encode to format the json to be more readable and doing so will add line breaks.
(Note that this option is available for PHP 5.4.0 and above)
I hope the above solution works for you.
Anyway I strongly suggest you to investigate further the issue in order to let the original code too to work.
First you should ensure you're running a recent and stable version of both nginx and php.
Then I would check nginx configuration file, php-fpm configuration (if you're using php-fpm) and finally php configuration.
Also check php, nginx, and php-fpm error logs.

try using php heredoc for echoing http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc

In case you don't have PHP version > 5.4.0 installed on your server a quick workaround could be something like this. The below snippet works for a test array. Initial test was with an array of 250Kb. Since i can't post the actual test array here is a test link with a smaller example. It is as the result of JSON_PRETTY_PRINT though.
$out = json_encode($arr,JSON_FORCE_OBJECT);
$out = str_replace( ':{', ':' . PHP_EOL . ' ' . '{', $out );
$out = str_replace( '},', PHP_EOL . ' },', $out );
$out = str_replace( ',', ',' . PHP_EOL . ' ', $out );
$out = str_replace( '},' . PHP_EOL . ' ', '},' . PHP_EOL . ' ', $out );
$out = str_replace( '}}', PHP_EOL . ' }' . PHP_EOL . '}', $out );
echo $out;

Related

php string concatenation "A<"."B" does not work

I'm writing a function to output HTML elements, the problem is: when I try to concatenate this two strings:
$tag = "<" . "tag";
The instruction echo $tag outputs nothing. What is wrong
As mentioned in comments, special characters like <, will be parsed by browser as HTML, therefore you won't see them as you expect.
Its almost the same thing:
$tag = 'p';
echo '<' . $tag '>' . Test . '</' . $tag . '>';
Which is the same as
echo '<p>' . Test . '</p>';
So after script execution you'll see just
Test
in a browser. but when viewing a source, it will be as
<p>Test</p>
If for some reason you want to see HTML tags, then you need to escape special chars using built-in function htmlentities().
In your case, you can just prepare a string, then just echo it like
echo htmlentities($string);
If by tag you mean an HTML entity then its not going to be seen in the browser. You may need to do a 'view source' to see what was created by echo call.

Not getting newlines in output when using PHP_EOL

I am putting together a string that I will output to a .srt file:
while ($row = mysql_fetch_array($res)) {
$srt = $srt . $row['line_number'] . PHP_EOL;
$srt = $srt . str_replace(".", ",", $row['start']) . " --> " . str_replace(".", ",", $row['end']) .PHP_EOL ;
$srt = $srt . br2nl($row['text']) . PHP_EOL;
$srt = $srt . PHP_EOL;
}
But it seems like PHP_EOL isn't working, because my output is:
100:00:02,107 --> 00:00:05,810you sure
and doesn't have any newlines. I am trying to get my output to be:
1
00:00:02,107 --> 00:00:05,810
you sure
followed by a newline.
It works when testing through localhost on my computer. Could the PHP version on my host be missing support for PHP_EOL?
The PHP manual says the PHP_EOL constant was available since PHP 4.3.10 and PHP 5.0.2
PHP_EOL (string)
The correct 'End Of Line' symbol for this platform. Available since PHP 4.3.10 and PHP 5.0.2 - http://php.net/manual/en/reserved.constants.php
So test to see if it exists:
var_dump(PHP_EOL); // should output: string(1) " "
OR
var_dump(defined("PHP_EOL")); // should output if exists: bool(true)
and if it is not defined, just define it manually if you want
define("PHP_EOL", "\n");
OR just use echo "\n" or echo "\r\n"
The other possible reason is when you output the $srt variable in your browser your outputting and the mime type is set in HTML and so you see it as one line, but if you view the source it should be spanned accross multiple lines.
To ensure text output you could echo out a <pre> tag if you want to keep html or at the top of your php file add this line to force text output:
header('Content-Type: text/plain', true);
PHP_EOL The correct 'End Of Line' symbol for this platform.
So it works on local host because its window and gives a windows line break
You online website is probably on linux and gives a linux line-break
To get a consistent result use "\r\n" instead of PHP_EOL, although I think media players will be a ble to recognize any style of line breaks.

printing a php variable as it is : with all the special characters

Ok I need to find out what is contained inside a PHP variable and I have it to do it visually, is there a function to display whatever that's contained in a string as it is?
For example :
$TEST = '&nbsp' . "\n" . ' ';
if I use echo the output will be :
while i want it to be :
&nbsp\n&nbsp
is it possible? (I hope I was clear enough)
ty
You can use json_encode with htmlspecialchars:
$TEST = ' ' . "\n" . ' ';
echo json_encode(htmlspecialchars($TEST));
Note that json_encode has third agrument in PHP 5.4.
var_dump() should do the work for you?
Example:
echo "<pre>";
var_dump($variable);
echo "</pre>";
Use <pre> to keep the format structure, makes it alot easier to read.
Resources:
http://php.net/manual/en/function.var-dump.php
http://www.w3schools.com/tags/tag_pre.asp
Try print_r, var_dump or var_export functions, you'll find them very handy for this kind of needs!
http://www.php.net/manual/en/function.htmlspecialchars.php
or
http://www.php.net/manual/en/function.htmlentities.php
$TEST = '&nbsp' . "\n" . ' ';
echo htmlspecialchars(str_replace('\n','\\n', $TEST), ENT_QUOTES);
or
$TEST = '&nbsp' . "\n" . ' ';
echo htmlentities(str_replace('\n','\\n',$TEST), ENT_QUOTES);
You may have to encode the newlines manually. If you want to encode them as actual newlines you can use nl2br. Or string replace these characters with your preference. Update: as I have added to the code per request. String replace special characters you wish to see like newlines and tabs.
assuming you want it for the debugging purposes, let me suggest to use urlencode(). I am using it to make sure I don't miss any invisible character.
The output is not that clear but it works for me.

A simple question in PHP but need help

To percent encode a input string (an XML file), only for % and line terminators..
Don't roll your own URL encoding. Use the built-in stuff.
$xml = urlencode($xml);
If I understood your question correctly, you'll need to do something like
$input .= 'datacenter: ' . str_replace(array('\n', '\r'), array('%0A', '%0D'), $xmlfile) . "\n";

PHP line break with file_put_contents()

I can't seem to figure out why the following code doesn't produce a new line in my text file - neither does using \n etc either - any ideas what could be wrong?
$data = $name . ' | ' . $_POST['comment'] . PHP_EOL;
//write to file
$f = file_put_contents('posts.txt', $data, FILE_APPEND);
Are you viewing the text file in an internet browser by any chance?
If you are, the browser will get rid of the newline characters (unless you're using PRE tags).
Try double quotes: $data = $name . ' | ' . $_POST['comment'] . "\n";
Or: $data = "$name | {$_POST['comment']}\n";
Have you tried \r or \n\r ? Just an idea.

Categories