Line break in PHP - php

I am trying to create a newline character in my foreach loop. After the URL I am trying to create a newline and then have a "------" between the title and content. After this there is supposed to be a space between the next URL. I have the space but I can't seem to get the line break. When I echo "\t" or "\n" in the loop nothing happens. When I use HTML in the loop it won't work, gives too many spaces.
for($i=0; $i < 4 ;$i++)
{
foreach ($json as $URL)
{
echo $URL ['results'][$i]['url'];
echo "---------------";
foreach ($json as $TITLE)
{
echo $TITLE ['results'][$i]['title'];
echo "--------";
}
foreach ($json as $content)
echo $content['results'][$i]['content'];
echo "---------------- ";
}
}
Is there a function in php besides "\n" or another way of manipulating the HTML to insert the line break?
TIA

There are two things you can do:
1: Use <br> as line break. If you use that, you should also consider using <hr> to insert the horizontal line.
some text<br>
<hr>
some other text<br>
2: Use <pre> and </pre> tags around your text to output preformatted text. You can then use \n and \t to format your text.
<pre>
some text\n
-------\n
some other text\n
</pre>

This might the one you are searching for
for($i=0; $i < 4 ;$i++)
{
foreach ($json as $URL)
{
echo $URL ['results'][$i]['url'];
echo "<br/>";
echo "---------------";
foreach ($json as $TITLE)
{
echo $TITLE ['results'][$i]['title'];
echo "--------";
}
foreach ($json as $content)
echo $content['results'][$i]['content'];
echo "---------------- ";
}
}

\n doesn't work in HTML. If you view source of the document you will however see the line breaks. Use html markup like
Test line break<br />
<p>paragraph</p>
<p>paragraph</p>

Simply add <br /> to echo statements. as in html we use this for line breaks.
echo "Content"."<br />";
This would give line breaks in HTML format.

use
echo "<br />";
instead of
echo "---------------- ";

Use echo '';
<?php
echo "first line.<br />Second line.';
?>
or nl2br() function,
<?php
echo nl2br("first line.\nSecond line.");
?>

You can consider
echo "<hr /> ";

Related

trying to get a form output on a request

I am trying to get values from a form but on Submit request. Bellow is just the PHP code as I know that the HTML Form is correct as it worked perfectly when I did not place the isset() function into the PHP.
<?php
if (isset($_POST["submit"]))
{
$fname = $_POST['firstname'];
$emailstr = $_POST['email'];
$postaddrstr =$_POST['postaddr'];
$favsportstr =$_POST['favsport'];
$emailliststr =$_POST['emaillist'];
}
?>
I believe the error lies somewhere in the below part as i am getting an undefined variable message for $val and an Array to string conversion at the foreach loop.
<section id="output">
<?php
if (isset($_POST["submit"]))
{
echo "<h2>The following information was received from the form:</h2>";
echo "<p><strong>First Name:</strong> $fname </p>";
echo "<p><strong>Email = </strong> $emailstr </p>";
echo "<p><strong>Post Address = </strong> $postaddrstr </p>";
echo "<p><strong>Your Favourit Sport:</strong>
foreach($favsportstr as $val) {
$val
}";
echo "<p><strong>Email list = </strong> $emailliststr </p>";
}
?>
</section>
You can't write loops inside echo change following line:
echo "<p><strong>Your Favourit Sport:</strong>
foreach($favsportstr as $val) {
$val
}";
to
echo "<p><strong>Your Favourit Sport:</strong> ";
foreach($favsportstr as $val) {
echo $val;
}
This is where your error comes from:
echo "<p><strong>Your Favourit Sport:</strong>
foreach($favsportstr as $val) {
$val
}";
Just change it to this and it will be fine:
echo "<p><strong>Your Favourit Sport:</strong>";
foreach($favsportstr as $val) {
echo $val;
}
The reason is you can't put a loop inside an echo statement. Put echo inside the loop not the loop inside echo. 'echo' statement is just for printing the output. It wont support any processing it will just print everything inside it. It can only output the variable values when they are placed between double quotes. Like this : echo "$var";

Generating a list from a text file in PHP

I am attempting to create an ordered list from a text file. As my code currently stands, it modifys the original text file with the input all on the same line(list number). e.g if I input "mercury" it will come out as 1. mercury, but if I input "venus", it will appear as 1.mercuryvenus
I am trying to get it to work so that if I input some text such as "mercury" and hit the submit button, it will appear as
1. mercury. If I input some more text such as "venus", it will appear as 2. venus, all in ordered list format. I assume that explode may be used for this, but I am unsure of how to implement this properly. Another option would be to create a new text file for each input if that were to be more efficient.
echo "<form method='post'>
<label>Enter some text</label><br>
<textarea name='textbox' cols='60' rows='5' required></textarea>
<br>
<input type='submit' name='submit' value='Submit'/>
<input type='hidden' name='step' value=''/>
</form>";
echo "<section>";
echo "<h3>Current tasks</h3>";
$text = ("text.txt");
$extract = (isset($_POST['textbox']) ? $_POST['textbox'] : null);
$file = fopen($text,"a");
fwrite($file,$extract);
fread($file,filesize("text.txt"));
fclose($file); #Not sure where this should really go
$c = array(file_get_contents('text.txt'));
$x = explode(" ",$c); #Could be wrong format
echo "<ol>";
foreach($c as $r) {
echo "<li>" . $r. "</li>", "<br>";
}
echo "</ol>";
echo "</section>";
Here is the solution
echo "<section>";
echo "<h3>Current tasks</h3>";
$text = "text.txt";
$extract = (isset($_POST['textbox']) ? $_POST['textbox'] : null);
$file = fopen($text,"a+");
fwrite($file," ".$extract);
#fread($file,filesize("$text"));
$x = explode(" ",file_get_contents($text));
if(isset($_POST['submit'])) {
echo "<ol>";
foreach ($x as $r) {
echo "<li>" . $r . "</li>", "<br>";
}
echo "</ol>";
echo "</section>"
First, the "a" in fopen($text,"a") means append. Which means if you already have the text "mercury" in your file and your run your program again with "venus", you will be appending "venus" on the end of "mercury" to get "mercuryvenus". If you want a space between the two, you will have to add it when your write it to file: fwrite($file, " ".$extract);
Second, you do $x = explode(... and then do not use $x in your foreach statement. Use $x instead of $c in your foreach.

PHP: preg_match not working

I have the following code:
$data = "Normal text
&nbsp&nbsp&nbsp&nbspcode
&nbsp&nbsp&nbsp&nbspcode
&nbsp&nbsp&nbsp&nbspcode
Normal text";
$data = nl2br($data);
$data= explode('<br />', $data );
foreach($data as $value){
if(preg_match('/^&nbsp&nbsp&nbsp&nbsp/',$value)){
echo 'code';
echo '<br />';
}else{
echo 'Not code';
echo '<br />';
}
}
I want to check if each of the lines starts with 4 spaces and if it does i want to echo as 'Code' and if it doesn't i want to echo as 'Not code'. But i am getting the output as 'Not code' though the 2nd , 3rd and 4th lines start with four spaces. I cannot figure out what I have done wrong. Please help me.
nl2br doesn't generate <br /> unless you tell it to. Your explode logic is wrong.
Instead, try this:
$data = "Normal text.......";
foreach(explode("\n",$data) as $line) {
// your existing foreach content code here
}
got it working
added a trim() to get rid of the newline in front of the string
nl2br replace \n with <br />\n (or <br />\r\n),
so when spliting on <br /> the \n is left as the first char
<?php
$data = "Normal text
&nbsp&nbsp&nbsp&nbspcode
&nbsp&nbsp&nbsp&nbspcode
&nbsp&nbsp&nbsp&nbspcode
Normal text";
$data = nl2br($data);
$data= explode('<br />', $data );
foreach($data as $value)
{
if(preg_match('/^&nbsp&nbsp&nbsp&nbsp/', trim($value)))
{
echo 'code';
}
else
{
echo 'Not code';
}
echo '<br />';
}
?>
You could also use "startsWith" as defined here...
https://stackoverflow.com/a/834355/2180189
...instead of the regexp match. That is, if the spaces are always at the beginning

Display white spaces that precede the content of the line of the file - PHP

I'm currently using foreach loop to display the contents of a text file. However, I want to also display the whitespaces that precede the actual content of the line. How to do so?
$loop_var = 0;
foreach($lines as $line) {
$loop_var++;
if ($loop_var == 1) {
echo'<div id="h1">' . $line . '</div>';
}
if ($loop_var == 2) {
echo '<div id="h2">' . $line . '</div><br />';
}
if ($loop_var > 2) {
if ($loop_var == 3) { echo '<pre><div id="code">'; }
echo ($line) . "<br />";
}
}
echo '</pre></div>';
Now, if the textfile contains the following:
blah
blah
blah
blah
It is getting displayed as:
blah
blah
blah
blah
Use <pre> tag, and print the content of textfile into this.
example:
print '<pre>'.file_get_contents('filename.txt').'</pre>';
Line By line (With conditions)
$file = fopen('filename','r');
print '<pre>';
$counter = 0;
while( $line = fgets($file) ){
if( /*the condition comes here whitch line you want to print. example: */ $counter >= 2 ){
print $line;
}
if( /*the condition comes here where wants you end the printing. example: */ $counter >= 10 )
$counter++;
}
print '</pre>';
fclose($file);
When you read text from a file and output that text again, the whitespace is still there.
But: if you are outputting HTML, and viewing the output in a browser, the whitespace is ignored. That's just the normal way html is displayed by a browser.
Use your browser to view the HTML source code (e.g. CTRL-U in firefox) to check if this is the case.
If you want the whitespace to be displayed in your webpage you can use the pre-Tag, or use the CSS property "whitespace" http://www.w3schools.com/cssref/pr_text_white-space.asp.
<pre><?php echo $file_content ?></pre>
or
<p style="whitespace:pre;"><?php echo $file_content ?></p>
See demo here: http://jsfiddle.net/bjelline/CjXMe/
Well, you can brute-force it if you wish ... only in case you're really stuck!
1) Get the length of the string with strlen()
2) Run a loop on the characters in the string and check for a space with strpos
3) Concatenate an html space to an empty string and print before-hand
$str = " whatever is in here ... ";
$spaces = "";
for( $i=0; $i<strlen($str); $i++ ){
if( strpos( $str, ' ', $i ) ){
$spaces .= " ";
}
}

How to print php code in HTML tags?

Hello i'm having this variable which is string.
$this->product_output_html = <<< HTML
Some HTML Code
HTML;
I want int he class test to add a php for loop like this one
if ($admin->errors) { foreach ($admin->errors as $error) {
echo ''.$error.''; } }
i have tried to add but is not working. i added '' after the class="test"> and before the of the test but still is not working. what i'm doing wrong?
thanks a lot
try something like
$this->product_output_html = 'Start of html code as a string';
if ($admin->errors) {
foreach ($admin->errors as $error) {
$this->product_output_html .= '<br />'.$error;
}
}
$this->product_output_html .= '<br />End of html code as a string';
echo $this->product_output_html;
replace
echo ".$error.";
with
echo $error;

Categories