I am returning data from three columns and displayed it with:
echo "<p><h3><span class='tyler'>".$results['COL 2']."</span></h3>".$results['COL 4'].$results['COL 3']."</p>";
This works fine. COL 4 is an actual URL and I am trying to put it in an anchor tag with COL 3 as the anchor text:
echo "<p><h3><span class='tyler'>".$results['COL 2']."</span></h3>""<a href=".$results['COL 4']"/>".$results['COL 3']."</a></p>";
I am trying to use this code but it doesn't work. My assumption is that the problem has something to do with the back to back quotes after the closing h3 tag. How would I go about making this work?
It can get confusing to build large strings that are output to HTML. This is what you have:
echo "<p><h3><span class='tyler'>"
.$results['COL 2']
."</span></h3>""<a href=".$results['COL 4']"/>"
.$results['COL 3']
."</a></p>";
I've broken it up to more clearly reference what is going on. In the third line (starting with the close-span tag), you have two double quotes right next to each other. Further on, you have quotes opening the close-slash part of the tag, but not a string concatenation operator (.). Finally, you are confusing double and single quotes. You want:
."</span></h3><a href='".$results['COL 4']."'/>"
But a better way of doing this would be to split out your components:
$title = $results['COL 2'];
$href = $results['COL 4'];
$anchor_text = $results['COL 4'];
// Here you can add debugging statements to ensure you have the right values.
$paragraph = "<p><h3><span class='tyler'>%s</span></h3><a href='%s'>%s</a></p>"
echo sprintf($paragraph, $title, $href, $anchor_text);
This method uses sprintf to 'slot in' the strings you want. It allows you to be more clear about building the html, without worrying about what the specific 'dynamic' values are. There are, of course, many other ways of doing this sort of 'templating'.
An Aside on String Building in PHP
This line of code assigns a simple string to a variable in PHP:
$message = "Hello world!";
This line of code 'concatenates' three strings using the concatenation operator (which is a dot: .):
$html = "<p>".$html."</p>";
This line would yield an equivalent result:
$html = "<p>Hello world!</p>";
This line will yield an error:
$bad = "<p>""Hello world!""</p>";
The reason it yields an error is because the language will 'tokenize' the code into something like:
<variable name> <assign> <string> <string> <string> <end statement>
Except that, semantically, three <string>s in a row doesn't make sense. It needs an 'operator' between them, like so:
<variable name> <assign> <string> <concatenate> <string> <concatenate> <string> <end statement>
PHP knows how to 'parse' this string of tokens. It will know to evaluate each string, and then concatenate them together. An intermediate stage becomes this:
<variable name> <assign> <string (composed of three previous strings)> <end statement>
It knows this because the concatenation operator tells it how to combine those strings.
That brings us back to using the dot/concatenation operator:
$html = "<p>Hello world!</p>";
Now, HTML markup looks like this:
SO Help Page
And when PHP 'outputs' the final result, all it is doing is 'echo'ing or 'printing' a string to the HTML response. Given that, and given that PHP interprets a double quote as the 'end' of a string, how do you put strings into a variable, so it prints out like the HTML above? This won't work, because PHP doesn't know how to interpret http://... in this context:
echo "SO Help Page";
There are a few ways to get around this. You can 'escape' the double quotes:
echo "SO Help Page";
By inserting a \ in the string before the double quote you signal to PHP to not end the string token, and to therefore parse the whole thing as a single string.
Alternatively, HTML also accepts single quotes for it's attribute values. So you can do this:
echo "<a href='http://www.stackoverflow.com/help'>SO Help Page</a>";
Which yields this on the HTML response:
<a href='http://www.stackoverflow.com/help'>SO Help Page</a>
Regardless of which way you go, you have to remember that the PHP code does not magically know that you're building an HTML page: it is simply constructing and printing strings to the HTML response. You have to tell it when to ignore parts of the string.
My point above is that for long enough PHP scripts, this can become confusing. So breaking down the strings into manageable chunks, so you can see what you're inserting and where things (like quotes, open and close tags, etc.) are makes your life easier.
Related
PHP-Beginner here looking for help, who's been trying for a full hour now to get this working.
I have a PHP line like this:
<td>'.$row["temperature"].'</td>
And I need to add a single quote ' to the front.
So, if $row["temperature"] is e.g. 9.77 the result is '9.77
I've tried to escape the single quote with a backslash, tried using double-quotes, etc. but I just can't get it working.
Can someone tell me how to get this working?
Examples which didn't work:
<td>'\'.$row["temperature"].'</td>
<td>"\'.$row["temperature"]."</td> //this gives me everything including the double quotes
<td>"\'.$row['temperature']."</td>
and many (failures) more...
Assuming that your first example is part of a longer expression like this:
echo 'Some more HTML markup <td>'.$row["temperature"].'</td> More Markup here too';
Then you're putting the leading ' in the wrong place. Include it in the preceding string:
$row = ['temperature'=>3];
echo 'Some more HTML markup <td>\''.$row["temperature"].'</td> More Markup here too';
// ^^ insert here
Output:
Some more HTML markup <td>'3</td> More Markup here too
See https://3v4l.org/o82U9
I am using a for loop to get the contects of a url that has paging in the form of pg=1
However I tried this without luck
$html= file_get_contents("http://www.........&pg='.$i.'");
Just remove the . characters from around the integer you're appending to the string. According to the PHP manual:
When a string is specified in double quotes or with heredoc, variables are parsed within it
(http://php.net/manual/en/language.types.string.php, section "Variable Parsing")
See http://ideone.com/AtcoYi for an example.
EDIT:
It's unclear to me whether the OP wants the string wrapped in single quotes in the output. If so, leave them in:
$html = file_get_contents("http://www.........&pg='$i'");
If not, take them out:
$html = file_get_contents("http://www.........&pg=$i");
watch the quote marks
$html= file_get_contents("http://www.........&pg=".$i);
I'm trying to write a php script that will generate a variety of new php pages, but I'm finding that I'm unable to write a square bracket out. When I escape a square bracket in the same way as other characters (ie [ ) the leading \ is written to the new page, which results in code that doesnt work:
echo $row\['Value'\];
When I do not escape the bracket, the page fails, and the same thing happens when I try and substitute asc(91).
I have seen other examples that use code like $row->Value, but I tried that and it didn't work. If anyone can help me output a square bracket, or knows of another method by which I can fetch a value from a row without using one at all, I'd be very grateful
Your echo would appear as an array reference to PHP. Try this:
echo $row, "['Value'];"
assuming that you want the value of $row to be output, and not the literal text $row. If you want the literal text, (e.g. you're trying to build a PHP script on the fly), then either of these should do the trick:
echo '$row[\'Value\'];';
echo "\$row['Value'];";
How about this:
echo sprintf("\$row['%s']", $value); // either scenario
echo sprintf("%s['Value']", $row);
Keep in mind that PHP automatically parses double quote strings ("), and tries to find variabels within. So, the bracket is probably not the issue, the $ variable prefix (coupled with the parser) probably is.
There are a couple other answers that work but I want to elaborate:
The "echo" construct can take a variable or a string. You can't echo a string to the screen in the same way that you do a variable. For example: echo hello; will not behave as you might think. You need to include it in quotes such as echo "hello";
You can also use single quotes. Single quotes and double quotes behave differently. For example:
$foo = "bar";
echo $foo;
echo "$foo";
echo '$foo';
The first will echo "bar", the second will also echo "bar" because PHP looks for variables in double quotes strings. The third will echo '$foo' because PHP does not try to do variable substitution in a single quoted string. So you can do (as #mark-b said):
echo "\$row['Value']";
or
echo '$row[\'Value\']';
Now, that $row->value syntax that you saw, is object notation. It is assuming that $row is an object and not an array. Objects are a whole other ballgame.
You're talking about code generation in your question, so I expect you also want to output the 'echo' statement in the generated code. Assuming you want to save the output into a file so it can be easily executed, you want to use something like fwrite or file_put_contents, I expect. You need to think in terms of strings, which can be a bit tricky when you're seeing code.
Something like this should work:
fwrite($fp, 'echo $row[\'Value\'];'."\n");
Note how the single and double quotes work. \n is resolved to a newline, but anything in the single quotes is treated as a string and is printed as is, apart from \', which should print a literal single quote in the output file.
Hope this helps.
I've hit a snag in a syntax highlighter I've been working on. PHP supports strings contained between both "" and ''. Unlike C#, which is more easily controlled by only allowing "", with the option # for automatically escaping the string.
If I have two strings, like so:
$code = "print( \"<div class='test'>content?div><div class='test'>content</div>\" );";
If I echo $code, I will get:
print( "<div class='test'>content?div><div class='test'>content</div>" );
Here's my problem. When I parse content between the starting quote and ending quote, I removed such content to be put back later (so I don't cross highlight), using a clipboard tool (just copy paste). I have it setup to parse content between '' first using regex. The end result (after both string types) will look like so:
print( "<div class=>content?div><div class=>content</div>" );
How can I modify my regex to look back (from start) and forward (from end) to look for the topmost string delimeter (' or "). It's hard to explain, hopefully someone gets it, otherwise I'll just have to live with it.
This is not possible with regular expressions; they are not powerful enough to deal with recursion. They cannot close nested parentheses correctly, they cannot close nested quotes correctly. You need a push-down automata (or a context-free language) at the least for this kind of functionality.
I have some php code in a database like so
$x = "<?php some code here ?>";
but I want to output that whole line to the browser without php evaluating it. Right now it is evaluating it unfortunately. I thought about escaping it but that didn't work. How might a person accomplish this?
Thanks
EDIT:
<?php
echo '<? hey ?>';
echo "<dog dog>";
?>
if I run that code the dog dog tag shows up in the browser source code where as <? hey ?> does not. It seems like it would still be evaluating it.
Edit, got the answer, thanks everyone.
Just do:
echo htmlspecialchars($x);
'Single quotes' tell PHP to interpert the string exactly as is. It will include all whitespace and characters exactly as is.
"Double Quotes" tell PHP to parse the string. This reduces whitespace, replaces variables, and parses any other magic string things.
Finally, `backticks` are used for shell commands.
If you are trying to display it in a browser exactly like that, you might want to try htmlentities($string).
Do you want it to appear like that? If so, you'll need to use < and > (strictly only the < is necessary) to encode the string.
use '(single quotes) instead of "(double quotes)
Ih PHP double quotes evaluate expressions, single quotes do not so:
$a = 123;
$b = "value of $a"; // value of 123
$c = 'value of $a'; // value of $a
The only problem with single quotes is they don't understand characters like \n for newlines (that will be printed as \n not a newline when put in single quotes).
So is all you need:
echo '<?php some code here ?>';
?
For more information see Strings in the PHP manual.
You're a bit unclear about what gets evaluated.
If you're talking about variables, there are plenty of correct answers here.
If you're talking about the <? ?> block, something's wrong. That string should not be evaluated if within a PHP block (If you mean the opening and closing PHP statements).
Maybe you are missing the opening and closing <? ?> before and after your operation?
If you're outputting php code you might even consider using highlight_string which will perform syntax highlighting on the input