The following PHP function outputs JS:
function dothething( $data ){
$res = "
<div id=\"blah\">
Here's some stuff, ". $data['name'] ."
</div>";
echo "$('#container').html('". $res ."');";
}
This function is called via jQuery's $.ajax(), using dataType: 'script' ... so whatever is echoed runs like a JS function. There's more to it of course, but my question has to do with encoding. The ajax will fail when $res contains newlines or apostrophes. So adding this above the echo seems to be working for now:
$res = str_replace("\n", "\\n", addslashes($res));
Is this the best way to format the PHP variable $res to yield valid javascript for ajax?
Is there anything else I should add in there?
In your case I would use json_encode() over anything else:
echo "$('#container').html(" . json_encode($res) . ");";
When applied to a string value, it will automatically encapsulate it with double quotes and escape anything inside that would otherwise cause a parse error.
Try this,
if(count($result)>0) {
$status = 0;
} else {
$status = 1;
}
$json['status'] = $status;
$json['result'] = $output;
print(json_encode($json));
Related
I'm quite new to PHP, so this is probably a stupid question.
I have an if/else that I need to use in a return tag, but it doesn't work. How should I structure this?
This is the tag:
return '… <div class="read"><a class="read-more hvr-icon-forward" href="'. get_permalink($post->ID) . '">' . "CODE HERE" . '</a></div>';
This is what I need to output in "CODE HERE"
$status = of_get_option('read_more');
if (empty($status)) {
echo 'Sorry, the page does not exist.';
} else {
_e($status);
}
https://jsfiddle.net/33nv1xpa/1/
Do I get it right, you have a structure like
return *SOME_STRING* SOME CODE WITH ";" *SOME_STRING*
?
I would highly recommend, to create a string var containing the text you want to return and finally only return that string.
$echoCode = result from CODE HERE
$returnText = "<div>blalba</div>" . $echoCode . "<div>blabla</div>";
return $returnText;
You can do it by using the ternary operator, and putting the variable assignment in parenthenses.
return "...". (($status = get_option('status')) ? $status : _e()) ."...";
Otherways, I suggest to put this functionality in a function, or at least in a plain variable.
Coding like this makes the whole thing unreadable.
Also, you're trying to run a wordpess function in an online parser which will undeniably miss these features!
Well you can use the Php eval function (http://php.net/manual/en/function.eval.php). It evaluates a string as Php code. So you can assign the result of eval to a variable called $code_here:
$code_here = "$status = of_get_option('read_more');
if (empty($status)) {
echo 'Sorry, the page does not exist.';
} else {
_e($status);
}";
$code_here = eval($code_here);
This block of PHP code prints out some information from a file in the directory, but I want the information printed out by echo to be used inside the HTML below it. Any help how to do this? Am I even asking this question right? Thanks.
if(array_pop($words) == "fulltrajectory.xyz") {
$DIR = explode("/",htmlspecialchars($_GET["name"]));
$truncatedDIR = array_pop($DIR);
$truncatedDIR2 = ''.implode("/",$DIR);
$conffile = fopen("/var/www/scmods/fileviewer/".$truncatedDIR2."/conf.txt",'r');
$line = trim(fgets($conffile));
while(!feof($conffile)) {
$words = preg_split('/\s+/',$line);
if(strcmp($words[0],"FROZENATOMS") == 0) {
print_r($words);
$frozen = implode(",", array_slice(preg_split('/\s+/',$line), 1));
}
$line = trim(fgets($conffile));
}
echo $frozen . "<br>";
}
?>
The above code prints out some information using an echo. The information printed out in that echo I want in the HTML code below where it has $PRINTHERE. How do I get it to do that? Thanks.
$("#btns").html(Jmol.jmolButton(jmolApplet0, "select atomno=[$PRINTHERE]; halos on;", "frozen on")
You just need to make sure that your file is a php file..
Then you can use html tags with php scripts, no need to add it using JS.
It's as simple as this:
<div>
<?php echo $PRINTHERE; ?>
</div>
Do remember that PHP is server-side and JS is client-side. But if you really want to do that, you can pass a php variable like this:
<script>
var print = <?php echo $PRINTHERE; ?>;
$("#btns").html(Jmol.jmolButton(jmolApplet0, "select atomno="+print+"; halos on;", "frozen on"));
</script>
I am working on a script with templates. So I have this PHP code:
<?php
$string = "TEST";
echo(file_get_contents('themes/default/test.html'));
?>
And I have this HTML (the test.html file):
<html>
<p>{$string}</p>
</html>
How can I make PHP actually display the variable inside the curly brackets? At the moment it displays {$string}.
P.S:
The string might also be an object with many many variables, and I will display them like that: {$object->variable}.
P.S 2: The HTML must stay as it is. This works:
$string = "I'm working!"
echo("The string is {$string}");
I need to use the same principle to display the value.
You can use the following code to achieve the desired result:
<?php
$string = "TEST";
$doc = file_get_contents('themes/default/test.html'));
echo preg_replace('/\{([A-Z]+)\}/', "$$1", $doc);
?>
P.S. Please note that it will assume that every string wrapped in { }
has a variable defined. So No error checking is implemented in the code above. furthermore it assumes that all variables have only alpha characters.
If it is possible to save your replacees in an array instead of normal variables you could use code below. I'm using it with a similar use case.
function loadFile($path) {
$vars = array();
$vars['string'] = "value";
$patterns = array_map("maskPattern", array_keys($vars));
$result = str_replace($patterns, $vars, file_get_contents($path));
return $result;
}
function maskPattern($value) {
return "{$" . $value . "}";
}
All you PHP must be in a <?php ?> block like this:
<html>
<p><?php echo "{" . $string . "}";?></p>
</html>
If you know the variable to replace in the html you can use the PHP function 'str_replace'. For your script,
$string = "TEST";
$content = file_get_contents('test.html');
$content = str_replace('{$string}', $string, $content);
echo($content);
It's simple to use echo.
<html>
<p>{<?php echo $string;?>}</p>
</html>
UPDATE 1:
After reading so many comments, found a solution, try this:
$string = "TEST";
$template = file_get_contents('themes/default/test.html', FILE_USE_INCLUDE_PATH);
$page = str_replace('{$string}',$string,$template);
echo $page;
I'm programming a bot on telegram and I didn't make the special keyboard via reply_mark up someone can help me?
My code is this:
file_get_contents($website."/sendmessage?chat_id=".$myID."&text=keyTest&reply_markup={"keyboard":[["test"]]}");
If I copy&paste your parameters to my bot and execute the command it works. But that's because I use the Text you provide as parts of my url.
api.telegram.org/bot[key]/sendMessage?chat_id=[id]&text=keyTest&reply_markup={"keyboard":[["test"]]}
What you are doing is writing a script that executes the command. As far as I can tell you're using the dot . to concatenate strings. Another thing you're doing is trying to write the JSON for the reply_markup directly into the url.
What your problem probably is, is one of the following: You're not escaping the " sign or not concatenating variables correctly.
So if keyboard and test are variables you need to concatenate them correctly using the dot:
file_get_contents($website."/sendmessage?chat_id=".$myID."&text=keyTest&reply_markup={".$keyboard.":[[".$test."]]}");
but if you just want to write your test keyboard into the string you need to escape the " so your string does not end:
file_get_contents($website."/sendmessage?chat_id=".$myID."&text=keyTest&reply_markup={\"keyboard\":[[\"test\"]]}");
Note: I have no idea if this is the correct way to escape " in php. This is just to explain your error. If you need to escape double quotes in php any other way, do it how it is supposed to be.
OK, I think that I have the solution for you!
So, this is the code:
$key = "{\"keyboard\":[ [\"OPTION1\"], [\"OPTION2\"], [\"OPTION3\"] ]}";
$url = $GLOBALS[API_URL]."/sendmessage?chat_id=$id&text=Choose%20your%20action&reply_markup=".urlencode($key);
file_get_contents($url);
Variable $GLOBALS[API_URL] = https://api.telegram.org/bot123456789:AAf6g4fr4rt5y67hadsffaerafasfasf
So replace my global var with your direct url or whatever :D
Other function that should be interesting for you is this:
function close_keyboard($id, $message)
{
//$text = "Keyboard_closed!";
$message = str_replace(" ", "%20", $message);
$key = "{\"hide_keyboard\":true}";
$url = $GLOBALS[API_URL]."/sendmessage?chat_id=$id&text=$messagge&reply_markup=".urlencode($key);
file_get_contents($url);
}
This function close your custom keyboard, and other my personal function is this:
function build_keyboard($elements, $message, $chat_id)
{
//Get length of array
$len = count($elements);
//Build custom keyboard
$keyboard = "{\"keyboard\":[ [\"";
for($i = 0; $i < $len; ++$i)
{
if($i < $len-1)
$keyboard .= $elements[$i]."\"],[\"";
else
$keyboard .= $elements[$i]."\"] ]}";
}
$url = $GLOBALS[API_URL]."/sendmessage?chat_id=$chat_id&text=".urlencode($message)."&reply_markup=".urlencode($keyboard);
file_get_contents($url);
}
Prototype of this function is build_keyboard(array(), String, String)
Example:
$messagge = "Wrong choise";
$keyboard = array("OPT1", "OPT2", "OPT3");
build_keyboard($keyboard, $message, $chat_id);
Remember that $message is always needed or reply_doesntt work!
Hope this will be usefull! You're welcome!
$var = "Hi there"."<br/>"."Welcome to my website"."<br/>;"
echo $var;
Is there an elegant way to handle line-breaks in PHP? I'm not sure about other languages, but C++ has eol so something thats more readable and elegant to use?
Thanks
For linebreaks, PHP as "\n" (see double quote strings) and PHP_EOL.
Here, you are using <br />, which is not a PHP line-break : it's an HTML linebreak.
Here, you can simplify what you posted (with HTML linebreaks) : no need for the strings concatenations : you can put everything in just one string, like this :
$var = "Hi there<br/>Welcome to my website<br/>";
Or, using PHP linebreaks :
$var = "Hi there\nWelcome to my website\n";
Note : you might also want to take a look at the nl2br() function, which inserts <br> before \n.
I have defined this:
if (PHP_SAPI === 'cli')
{
define( "LNBR", PHP_EOL);
}
else
{
define( "LNBR", "<BR/>");
}
After this use LNBR wherever I want to use \n.
in php line breaks we can use PHP_EOL (END of LINE) .it working as "\n"
but it cannot be shown on the ht ml page .because we have to give HTML break to break the Line..
so you can use it using define
define ("EOL","<br>");
then you can call it
I ended up writing a function that has worked for me well so far:
// pretty print data
function out($data, $label = NULL) {
$CLI = (php_sapi_name() === 'cli') ? 'cli' : '';
$gettype = gettype($data);
if (isset($label)) {
if ($CLI) { $label = $label . ': '; }
else { $label = '<b>'.$label.'</b>: '; }
}
if ($gettype == 'string' || $gettype == 'integer' || $gettype == 'double' || $gettype == 'boolean') {
if ($CLI) { echo $label . $data . "\n"; }
else { echo $label . $data . "<br/>"; }
}
else {
if ($CLI) { echo $label . print_r($data,1) . "\n"; }
else { echo $label . "<pre>".print_r($data,1)."</pre>"; }
}
}
// Usage
out('Hello world!');
$var = 'Hello Stackoverflow!';
out($var, 'Label');
Not very "elegant" and kinda a waste, but if you really care what the code looks like you could make your own fancy flag and then do a str_replace.
Example:<br />
$myoutput = "After this sentence there is a line break.<b>.|..</b> Here is a new line.";<br />
$myoutput = str_replace(".|..","<br />",$myoutput);<br />
or
how about:<br />
$myoutput = "After this sentence there is a line break.<b>E(*)3</b> Here is a new line.";<br />
$myoutput = str_replace("E(*)3","<br />",$myoutput);<br />
I call the first method "middle finger style" and the second "goatse style".
Because you are outputting to the browser, you have to use <br/>. Otherwise there is \n and \r or both combined.
Well, as with any language there are several ways to do it.
As previous answerers have mentioned, "<br/>" is not a linebreak in the traditional sense, it's an HTML line break. I don't know of a built in PHP constant for this, but you can always define your own:
// Something like this, but call it whatever you like
const HTML_LINEBREAK = "<br/>";
If you're outputting a bunch of lines (from an array of strings for example), you can use it this way:
// Output an array of strings
$myStrings = Array('Line1','Line2','Line3');
echo implode(HTML_LINEBREAK,$myStrings);
However, generally speaking I would say avoid hard coding HTML inside your PHP echo/print statements. If you can keep the HTML outside of the code, it makes things much more flexible and maintainable in the long run.
\n didn't work for me. the \n appear in the bodytext of the email I was sending.. this is how I resolved it.
str_pad($input, 990); //so that the spaces will pad out to the 990 cut off.