its a simple logger function. I want to load an array to a DIV content:
document.getElementById('layout').innerHTML = '<?php foreach ($logs as $item) { echo str_replace(array('"',"'"), array ('"','''), $item).'<hr />'; } ?>';
because $logs can contain HTML elements, but not quotes, since they would ruin the echoing. It should be OK, but Firefox say "malformed Unicode character sequence" and it doesnt displayed. Now what?
use html entities to translate your html code into safe sequencies
I might be wrong, but it looks like you're trying to enter php code into your page using javascript. Javascript is client side, so if anything, you will get the full code, not the parsed code.
If you want the php to be run beforehand, so the actual code in your page will be a javascript that has the allready-parsed contents in it, you neet to make a string that contains the finished content AND add "'" for javascript to understand it.
This might look like this (haven't checked the foreach for you)
<?//this part is parsed before sending it to the client
$conts = "'";
foreach ($logs as $item) {
$conts .= str_replace(array('"',"'"), array ('"','''), $item);
$conts .= "<hr/>";
}
$conts .= "'";
?>
document.getElementById('layout').innerHTML = <? echo $conts ?>;
Related
I'm writing an if statement in which a button needs to show if the cart is empty.
For this button I need to get the form key of the product for the data-url
So something like this:
Order
As mentioned above I need to wrap this button in an if statement, so something like this:
<?php
$_helper = Mage::helper('checkout/cart');
if (1 > $_helper->getItemsCount()){
echo 'Order';
}
else{
'<p>hello</p>';
}
?>
But obviously I can't have php echo within echo. Can anybody point me in the right direction of how to do this?
You don't put PHP inside HTML inside PHP. Since you're already in the context of PHP code, just concatenate the values you want to the output:
echo 'Order';
The resulting output is always just a string. You can simply build that string with whatever values you have.
You can just use string concatenation:
echo '<a href="#" data-url=".../' . Mage::getSingleton(...) . '"' ...
Simply don't open PHP up again. You can terminate the HTML interpretation inside an echo.
Your code should look like this:
<?php
$_helper = Mage::helper('checkout/cart');
if (1 > $_helper->getItemsCount()) {
echo 'Order';
}
else {
'<p>hello</p>';
}
?>
I have a sytem where I want to build an HTML table in PHP from data retrieved from a databse.
I've previously used two different methods for creating the HTML and echoing it.
Building a return variable, and echoing at the end of the PHP script:
<?php
$data['category']['parts']; // format of the data
$retval = '<table>';
foreach($data as $category) {
$retval .= '<tr>';
foreach($category as $data) {
$retval .= '<td>'.$data.'</td>'
}
$retval .= '</tr>';
}
$retval .= '</table>';
echo $retval;
The other method is to echo each line as the code comes to it:
<?php
$data['category']['parts']; // format of the data
echo '<table>';
foreach($data as $category) {
echo '<tr>';
foreach($category as $data) {
echo '<td>'.$data.'</td>'
}
echo '</tr>';
}
echo '</table>';
Which of the two methods is more efficient, in terms of processor/memory usage, and also for processing speed?
Is there actually a real difference, rather than just a question of style?
My shot is: whatever you find more readable. Impact on performance is so small that probably you won't see any difference.
However, if you really care, echo should be faster (nothing better than a performance test on your specific scenario) because string concatenation will resize retval multiple times (and this will impact performance).
Even better you should avoid concatenation also in your echo:
<?php
$data['category']['parts']; // format of the data
echo '<table>';
foreach($data as $category) {
echo '<tr>';
foreach($category as $data) {
echo '<td>', $data, '</td>';
}
echo '</tr>';
}
echo '</table>';
Do you want to do better? Just construct your own string builder object (but, honestly, gain is so small that you should seriously consider if worth your effort).
If you want to use kind of a templating to generate your page, I would rewrite your code to something like this.
(this can be in a dedicated file, and just included to display output)
<?php
$data['category']['parts']; // format of the data
?>
include ('templates/theFileIWantToShow.php');
---- snip files here. Processing above, template bellow.
<table>
<?foreach($data as $category):?>
<tr>
<?foreach($category as $data):?>
<td><?=$data?></td>
<?endforeach;?>
</tr>
<?endforeach;?>
</table>
This would offer (imho) best readability when it comes down to large html pages with only a few wildcards.
Advantages:
You get clean html with only a few spots of php in between
You can easily replace the template files without touching the generating code
you can reuse templates. Providing direct output and/or building strings is a mess, when it comes down to reuse the same html-markup for a certain element over and over.
Note that this requires shorttags to be enabled in your php.ini for PHP < 5.4.0.
Here's the problem, I am trying to echo a statement or an array after dynamically generated HTML, and unfortunately the thing that i want to echo goes above the HTML, is there any way to echo it after that dynamic HTML or work around?
Code:
Link 1
Link 2
if(isset($_GET["id"]) && $_GET["id"] == "do_something") {
$html = "dynamic html generate";
echo $html;
//after this im using foreach
foreach($array as $item) { echo $item . "<br />"; }
}
As I click one of these two , dynamically generated HTML shows up. Now for example I have an array:
$array = array("error1", "error2");
All the generated PHP goes above the dynamic HTML :/.
How should i fix it so that i can echo all of this array below the dynamic HTML?
Thanks
Use buffering with ob_start
ob_start();
// dynamic html code generate
$dynamic_html = ob_get_clean();
echo $dynamic_html;
// your code
echo $dynamic_html;
Sounds like you missed some closing tags (most likely </table>) in the dynamic html. Thats why the later generated echo gets displayed at the top.
Example (Note the missing closing table):
<?php
echo "<table><tr><td>TableText</td></tr>";
echo "I should be bellow the table, but going to the top.";
?>
will produce:
I should be bellow the table, but going to the top.
TableText
I have a PHP script that generates some Javascript for me in a manner like this:
foreach ($array as $element)
{
echo '<a onClick="myFunctionTakesPHPValues('.$element[0].','.$element[1].')">'.$element[2].'</a>';
}
My problem is that how can I escape so that the Javascript bit will look more like
<a onClick='MyFunctionTakesPHPValues("'.$element[0].','.$element[1].'")>'.$element[2].'</a>';
I hope this makes sense. The short version is that I feel i need triple quotes inside double quotes inside single quotes, but there is no such thing as triple quotes, but I believe there is some way to escape quotes to nest it up three times.
Same as always: encode as JSON.
echo '<a onClick="myFunctionTakesPHPValues('.json_encode($element[0]).','.json_encode($element[1]).')">'.$element[2].'</a>';
Never echo JS from PHP. Escape from PHP mode instead, it will save you a lot of slashes and nerves.
Every value have to be escaped properly, as explained in this article
So, for the JS values you have to escape them with json_encode() and, as they are going into HTML attribute, escape them as HTML too.
For the last element only HTML encoding is required.
foreach ($array as $element)
{
$param1 = htmlspecialchars(json_encode($element[0])); // better give them
$param2 = htmlspecialchars(json_encode($element[1])); // meaningful names
$param3 = htmlspecialchars($element[2]);
?>
<a onClick="myFunctionTakesPHPValues(<?=$param1?>,<?=$param2?>)">
<?=$param3?>
</a>
<? }
And yes, using raw JS in HTML attributes considered as a bad practice.
Use Like
echo "<a onClick='myFunctionTakesPHPValues(\"".$element[0]."\",\"".$element[1]."\")'>".$element[2]."</a>";
Use this:
echo "<a onClick='MyFunctionTakesPHPValues(\"'".$element[0]."','".$element[1]."'\")>'".$element[2]."'</a>'";
foreach ($array as $element)
{?>
<a onClick="myFunctionTakesPHPValues("<?php echo $element[0].','.$element[1].')>'.$element[2].'</a>'
}
?>
I haven't found anytihng in Google or the PHP manual, believe it or not. I would've thought there would be a string operation for something like this, maybe there is and I'm just uber blind today...
I have a php page, and when the button gets clicked, I would like to change a string of text on that page with something else.
So I was wondering if I could set the id="" attrib of the <p> to id="something" and then in my php code do something like this:
<?php
$something = "this will replace existing text in the something paragraph...";
?>
Can somebody please point me in the right direction? As the above did not work.
Thank you :)
UPDATE
I was able to get it working using the following sample:
Place this code above the <html> tag:
<?php
$existing = "default message here";
$something = "message displayed if form filled out.";
$ne = $_REQUEST["name"];
if ($ne == null) {
$output = $existing;
} else {
$output = $something;
}
?>
And place the following where ever your message is to be displayed:
<?php echo $output ?>
As far as I can get from your very fuzzy question, usually you don't need string manipulation if you have source data - you just substitute one data with another, this way:
<?php
$existing = "existing text";
$something = "this will replace existing text in the something paragraph...";
if (empty($_GET['button'])) {
$output = $existing;
} else {
$output = $something;
}
?>
<html>
<and stuff>
<p><?php echo $output ?></p>
</html>
but why not to ask a question bringing a real example of what you need? instead of foggy explanations in terms you aren't good with?
If you want to change the content of the paragraph without reloading the page you will need to use JavaScript. Give the paragraph an id.<p id='something'>Some text here</p> and then use innerHTML to replace it's contents. document.getElementById('something').innerHTML='Some new text'.
If you are reloading the page then you can use PHP. One way would be to put a marker in the HTML and then use str_replace() to insert the new text. eg <p><!-- marker --></p> in the HTML and $html_string = str_replace('<!-- marker -->', 'New Text', $html_string) assuming $html_string contains the HTML to output.
If you are looking for string manipulation and conversion you can simply use the str_replace function in php.
Please check this: str_replace()
If you're using a form (which I'm assuming you do) just check if the variable is set (check the $_POST array) and use a conditional statement. If the condition is false then display the default text, otherwise display something else.