Create variable with multiple lines of html in php - php

In perl I can qq[] to put multiple lines of html into a variable as shown below.
PERL
my $rank = 1;
my $name = 'John';
sub writeMsg
{
$test = qq[
<h1>User Ranking</h1>
<p>$name is ranked number $rank</p>
<p>lots more info to go in here</p>
];
return $test;
}
print writeMsg($rank, $name);
In php I can't seem to find a way to do this?
The soloution I have below returns the same result but it is already a lot harder to read and keep the syntax right,
PHP
$rank=1;
$name = 'John';
function writeMsg($rank, $name) {
$test = '<h1>User Ranking</h1>' . $name . ' is ranked number ' . $rank ' <p>lots more info to go in here</p>';
return $test;
}
print writeMsg($rank, $name);
Is there a way to do this in php? I am familiar with doing something similar in a foreach with the below syntax but haven't been able to come up with a good way to do this for a variable?
<?php foreach ($get_tests as $test): ?>
<?php endforeach; ?>

You just need to use " instead of '
$test= "
<h1>User Ranking</h1>
<p>$name is ranked number $rank</p>
<p>lots more info to go in here</p>
";

You can use the heredoc (http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc):
<?php
$str = <<<"EOD"
<p>Example of string</p>
<b>spanning multiple lines</b>
<p>using nowdoc syntax.</p>
EOD;
echo $str;
Edit: make sure to use double quotes

Related

Attempting to use variables that are stored within cell data

I am facing a problem that doesn't allow variables retrieved from cell data to appear as the declared variable on my web page. I will post an example below ;
email.db - Below represents the cell data for column email_body
email_body = Hi, $name
$name = $row['name'];
$messagebody = $row["email_body"];
$message = "
<html>
<body>
<p>".$messagebody."</p>
</body>
</html>
;
"
As you can see I'm attempting to make $row['name'] appear within $messagebody (which is text stored in a DB). The issue i'm having is that the above code will display $messagebody, but the $name variable will display as plain text and will ignore the variable.
Your help is appreciated,
Thanks.
Daniel - I think you might not have the exact right idea about how variables are rendered inside of PHP strings.
However, there is a function called sprintf that might be the tool to do what you're attempting to do!
sprintf (string $format [, mixed $... ])
The first $format argument in your case would be 'Hi, %s' - the %s being a stand-in for another string, $name. The function would then return 'Hi, Bobby', were $name set to bobby. (And name was passed as the second arg.)
// Re-set the data inside of `email_body` to 'Hi, %s';
// "%s" is a placeholder that hints that a string should be placed there
$name = $row['name'];
$messagebody = sprintf($row["email_body"], $name);
$message = "<html>
<body>
<p>".$messagebody."</p>
</body>
</html>";
You are attempting to evaluate PHP code in a string. That is generally unsafe. Instead of that, you can replace the placeholders (e.g. $name) with the actual values.
Example:
$messagebody = "Hi, $name!"
$compiledmessagebody = preg_replace('/\$name/', 'Daniel V.', $messagebody);
$message = "
<html>
<head><title></title><head>
<body>
<p>".$compiledmessagebody."</p>
</body>
</html>
";
EDIT: actually, it would be better to use a templating engine to do the above and much more out of the box. Pug goes nicely with PHP https://www.phug-lang.com/
I would use HEREDOC syntax:
$name = $row['name'];
$messagebody = $row['email_body'];
$message = <<<HTML
<html>
<body>
<p>$messagebody</p>
</body>
</html>
HTML;
That way you don't have to worry about breaking out of strings and multi-line strings appear much neater.
Technically, you don't need to break out of a double quoted string when using a simple variable like you were doing.
With HEREDOC syntax the last HTML; needs to be pushed all the way to the left. In this case I am using HTML as an identifier, but you can rename the identifier to something else.

PHP: How can I put HTML Code with PHP Code within into a PHP Variable?

I have a question about " and ' in PHP. I have to put a complete <li> element into a PHP variable but this doesn't work, the output is completely false...
$list =
"
<li class=\"<?php if($info[1] < 700) {echo \"half\";} else {echo \"full\";} ?>\">
<div class=\"onet-display\">
<?php if ($image = $post->get('image.src')): ?>
<a class=\"onet-display-block\" href=\"<?= $view->url('#blog/id', ['id' => $post->id]) ?>\"><img class=\"onet-thumb\" src=\"<?= $image ?>\" alt=\"<?= $post->get('image.alt') ?>\"></a>
<?php endif ?>
<h1 class=\"onet-thumb-title\"><?= $post->title ?></h1>
<div class=\"uk-margin\"><?= $post->excerpt ?: $post->content ?></div>
</div>
</li>
";
Is it because there is PHP Content in the HTML Code? How can I solve this?
Can someone help me and explain why this doesn't work?
<?php ... <?php
Since your string contains PHP tags, I suppose you expect them to be evaluated. The opening PHP tag within another PHP tag is interpreted as a part of the PHP code. For example, the following outputs <?php echo time();:
<?php echo "<?php echo time();";
There are several ways to build a PHP string from PHP expressions.
Concatenation
You can create functions returning strings and concatenate the calls to them with other strings:
function some_function() {
return time();
}
$html = "<li " . some_function() . ">";
or use sprintf:
$html = sprintf('<li %s>', some_function());
eval
Another way is to use eval, but I wouldn't recommend it as it allows execution of arbitrary PHP code and may cause unexpected behavior.
Output Buffering
If you are running PHP as a template engine, you can use the output control functions, e.g.:
<?php ob_start(); ?>
<li data-time="<?= time() ?>"> ...</li>
<?php
$html = ob_get_contents();
ob_end_clean();
echo $html;
Output
<li data-time="1483433793"> ...</li>
Here Document Syntax
If, however, the string is supposed to be assigned as is, use the here document syntax:
$html = <<<'HTML'
<li data-time="{$variable_will_NOT_be_parsed}">...</li>
HTML;
or
$html = <<<HTML
<li data-time="{$variable_WILL_be_parsed}">...</li>
HTML;
You want to store some html into a variable.
Your source should (if not yet) start with
<?php
Then you start building the contents of $list.
Starting from your code the nearest fix is to build $list by appending strings:
<?php
$list = "<li class=";
if($info[1] < 700)
{
$list .= "\"half\""; // RESULT: <li class="half"
}
else
{
$list .= "\"full\""; // RESULT: <li class="full"
}
// ...and so on...
Now a couple things to note:
$list .= "... is a short form of $list = $list . "...
Where the . dot operator joins two strings.
Second thing you may make code easier to read by mixing single and double quotes:
Use double quotes in PHP and single quotes in the generated HTML:
<?php
$list = "<li class=";
if($info[1] < 700)
{
$list .= "'half'"; // RESULT: <li class='half'
}
else
{
$list .= "'full'"; // RESULT: <li class='full'
}
// ...and so on...
This way you don't need to escape every double quote
i think you have to work like this
$test = "PHP Text";
$list = "<strong>here ist Html</strong>" . $test . "<br />";
echo $list;

Run PHP and HTML code from a string

I have a string stored in a variable in my php code, something like this:
<?php
$string = "
<?php $var = 'John'; ?>
<p>My name is <?php echo $var; ?></p>
";
?>
Then, when using the $string variable somewhere else, I want the code inside to be run properly as it should. The PHP code should run properly, also the HTML code should run properly. So, when echoing the $string, I will get My name is John wrapped in a <p> tag.
You don't want to do this. If you still insist, you should check eval aka evil function. First thing to know, you must not pass opening <?php tag in string, second you need to use single quotes for php script You want to evaluate (variables in single quotes are not evaluated), so your script should look something like:
<?php
$string = '
<?php $var = "John"; ?>
<p>My name is <?php echo $var; ?></p>
';
// Replace first opening <?php in string
$string = preg_replace('/<\?php/', '', $string, 1);
eval($string);
However, this is considered very high security risk.
So if I'm right, you have the $var = 'John'; stored in a different place.
Like this:
<?php $var = 'John'; ?>
And then on a different place, you want to create a variable named $String ?
I assume that you mean this, so I would suggest using the following:
<?php
$String = "<p>My name is ".$var." </p>";
echo $String;
?>
You should define $var outside the $string variable, like this
<?php
$var="John";
$string = "<p>My name is $var</p>";
?>
Or you can use . to concatenate the string
<?php
$var="John";
$string = "<p>My name is ".$var."</p>";
?>
Both codes will return the same string, so now when doing
<?php
echo $string;
?>
You will get <p>My name is John</p>

Stopping php returning the same result multiple times

I am trying to display a list of friends using PHP and SQL, and my code partially works. However, it is returning the same result on multiple occasions and I would like it not to.
The SQL:
$sql =
"SELECT ubuser.usr_firstname, ubuser.usr_lastname, ubuser.usr_DOB,
ubuser2_1.usr_firstname & \" \" & ubuser2_1.usr_lastname
AS UBFriend, ubFriendsLink.ub_lnkID1, ubFriendsLink.ub_lnkID2, ubuser.usr_ID,
ubuser2_1.usr_ID
FROM ubuser
AS ubuser2_1
INNER JOIN (ubFriendsLink INNER JOIN ubuser ON ubFriendsLink.ub_lnkID1 = ubuser.usr_ID)
ON ubuser2_1.usr_ID = ubFriendsLink.ub_lnkID2
WHERE (((ubFriendsLink.ub_lnkID1) = ".$_SESSION['usr_ID'] ."))
OR (((ubFriendsLink.ub_lnkID2) = ".$_SESSION['usr_ID'] ."))";
The SQL works (or seems to).
The code for displaying the result:
<?php
$nrecs=0;
while (!$FriendsRs->EOF) {
$nrecs++;
?>
<? php
if (.$SESSION['usr_ID'] == ['ub_lnkID1'])
{
echo <p>Name: <?php echo $FriendsRs->Fields['UBFriend']->Value ?><br/ >
<? php
else
echo <p>Name: <?php echo $FriendsRs->Fields['usr_firstname']->Value ?> <?php
echo $FriendsRs->Fields['usr_lastname']->Value ?><br />
<?php $FriendsRs->MoveNext() ?>
<?php } ?>
The result:
Name: Carl Smith
Name: Rob Sanderson
Name: Rob Sanderson
Name: Tony Jackson
The problem seems to be that what I am getting is a list of the names associated with the ub_lnkIDs, where i only want to display the individual names. (FYI, Rob Sanderson is not needed, but it can be returned once).
EDIT:
The desired output is
Name: Carl Smith
Name: Tony Jackson
From what you've described it sounds like you want to remove the duplicates from your list.
I'm not sure what you're trying to do with the session check but your original if/else condition didn't make sense so I changed it to what might be right based on your query.
<?php
$Arrnames = array();
// Produces array containing all the names in the correct format
while (!$FriendsRs->EOF)
{
if ($SESSION['usr_ID'] == $FriendsRs->Fields['ub_lnkID1'])
{
array_push($Arrnames, "<p>Name: ".$FriendsRs->Fields['UBFriend']->Value."<br />");
}
else
{
array_push($Arrnames, "<p>Name: ".$FriendsRs->Fields['usr_firstname']->Value ." ". $FriendsRs->Fields['usr_lastname']->Value . "<br />");
}
$FriendsRs->MoveNext();
}
// Removes the duplicates from the array
$ArrnamesDedupped = array_unique($Arrnames);
// Loops the de-duplicated array and echos the result
foreach ($ArrnamesDedupped as $value)
{
echo $value;
}
?>
if (.$SESSION['usr_ID'] == ['ub_lnkID1'])
My best guess is the single = is causing your if statement to fail
== means is the same as (and can return false) WHEREAS = will always return true! (= is used for setting values.)
Additionally you open <?php tags above the if statement - and then open them again in your <?php echo without closing them?
<? php
if (.$SESSION['usr_ID'] = ['ub_lnkID1'])
{
echo <p>Name: <?php echo //HERE
There are multiple problems.e.g. opening
php tags inside php tags, no closing } for the if clause, html paragraphs (p) opened and not closed etc.
what I think you want to do (not tested):
<?php
$nrecs = 0;
while (!$FriendsRs->EOF) {
$nrecs++;
if ($SESSION['usr_ID'] !='ub_lnkID1') {
echo "<p>Name:" . $FriendsRs->Fields['usr_firstname']->Value . " " . $FriendsRs->Fields['usr_lastname']->Value . "</p>";
}
$FriendsRs->MoveNext();
}
?>

How to rewrite this php function into HTML-emeddable function <?php ?>

Could someone convert this line of code to be readable by HTML?
echo '<h3>'. $r['title'] .'</h3>';
into something like this:
<?php echo...blah blah blah ?> /* To display the title in HTML */
I am sure I am not doing it right, that's why it's still not working :(.
Edit: There seems to be a confusion here. I am not going to modify the original php function. What I need to do is call it to my HTML page, to display the Title of the page
function r($text, $level = 3)
{
$tag = 'h' . $level . '>';
return '<' . $tag . $text . '</' . $tag;
}
Thanks for the downvote. The given question is totally unclear and constantly edited.
Ah you mean?
<php echo "<h3>$r['title']</h3>"; ?>
could be an answer to this unclear question
Save the result into a variable.
<?php $title = '<h3>'. $r['title'] .'</h3>';?>
<?php echo $title; ?>
Not exactly sure what you're asking, but you can't use PHP code within an HTML page.
The line
<?php echo '<h3>'. $r['title'] .'</h3>'; ?>
Within a PHP file, will print out the contents of $r['title'], within <h3> tags.
There is no function involved; $r is an associative array variable and title is a key to a particular value.

Categories