I want to write some html code in php. In this html code I am calling a javascript function. but while it is calling the function there is a problem. I think the problem is quotes but I couldn't fix it.
This is the html code that I want to put inside php.
<table>
<tr>
<img src="s.png" name="img">
</tr>
</table>
and this is my javascript code;
<script type="text/javascript">
img1 = "s.png";
img2 = "k.png";
function chng(c_img) {
if (document[c_img].src.indexOf(img1)!= -1) document[c_img].src = img2;
else document[c_img].src = img1;
}
</script>
How can i write this html inside php code?
Thanks
<?php
// your php code
?>
<table>
<tr>
<img src="s.png" name="img">
</tr>
</table>
<?php
// your php code
?>
<script type="text/javascript">
img1 = "s.png";
img2 = "k.png";
function chng(c_img) {
if (document[c_img].src.indexOf(img1)!= -1) document[c_img].src = img2;
else document[c_img].src = img1;
}
</script>
<?php
you also could wrap your code in heredoc, and echo it afterwards http://www.php.net/manual/de/language.types.string.php#language.types.string.syntax.heredoc
you could echo the html; eg
echo "<table>
<tr>
<img src=\"s.png\" name=\"img\">
</tr>
</table>
";
Just escape the double quotes with a backslash.
You can use PHP heredoc syntax:
var $js = <<<JS
// code
JS;
Escapes and echo "<html_code>" is a noob style.
Use scriptlets and the command echo.
<?
echo "<script type=\"text\/javascript\">"
?>
and so far. But pay attention of masking quotations signs and backslashes, etc.
Write html tags inside php code isn't nice. Read about templates to php as Smarty
http://www.smarty.net/
Related
I'm trying to convert my sample HTML output into a plain text but I don't know how. I use file_get_contents but the page which I'm trying to convert returns most like the same.
$raw = "http://localhost/guestbook/profiles.php";
$file_converted = file_get_contents($raw);
echo $file_converted;
profiles.php
<html>
<head>
<title>Profiles - GuestBook</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<!-- Some Divs -->
<div id="profile-wrapper">
<h2>Profile</h2>
<table>
<tr>
<td>Name:</td><td> John Dela Cruz</td>
</tr>
<tr>
<td>Age:</td><td>15</td>
</tr>
<tr>
<td>Location:</td><td> SomewhereIn, Asia</td>
</tr>
</table>
</div>
</body>
</html>
Basically, I trying to echo out something like this (plain text, no styles)
Profile
Name: John Dela Cruz
Age: 15
Location: SomewhereIn, Asia
but i don't know how. :-( . Please help me guys , thank you in advance.
EDIT: Since i am only after of the content of the page, no matter if it's styled or just a plain text , is there a way to select only (see code below) using file_get_contents() ?
<h2>Profile</h2>
<table>
<tr>
<td>Name:</td><td> John Dela Cruz</td>
</tr>
<tr>
<td>Age:</td><td>15</td>
</tr>
<tr>
<td>Location:</td><td> SomewhereIn, Asia</td>
</tr>
</table>
Use php strip_tags
If strip_tags is not working for then maybe you can use regex to extract the info you want.
Try using PHP preg_match with /(<td>.*?<\/td>)/ as the pattern
Have a look at simplexml_load_file():
http://www.php.net/manual/en/function.simplexml-load-file.php
It will allow you to load the HTML data into an object (SimpleXMLElement) and traverse that object like a tree.
try to use PHP function strip_tags
try this one,
<?php
$data = file_get_contents("your_file");
preg_match_all('|<div[^>]*?>(.*?)</div>|si',$data, $result);
print_r($result[0][0]);
?>
I have try this one, and it seems work for me, for you too i hope
You can use the strip_tags php function for this. Browse through the comments in the php manual page of the strip_tags function to see how you can use this in a good way.
PHP code (functions.php)
$main = $db_sql->query_array("SELECT catid,titel,subcat,startorder FROM $cat_table WHERE catid='$subcat'");
$tpl->register('category_title',stripslashes($main['titel']));
$tpl->register('category_id',$main['catid']);
So I want to add an if statement where if {category_id} is not 0 then do the following code
<img src="{GRAFURL}/{category_id}.jpg" alt="{category_title}" width="50" height="50" border="0" align="middle" /> {category_title}
what would be the correct syntax?
need more code still for the html file?
HTML doesn't have dynamic features like if-statements. Think of HTML as a language to define a layout - unchangeable using HTML itself.
This should do the trick:
<?php
if ( false === is_empty( $category_id )) {
echo "<img src='{$GRAFURL}/{$category_id}.jpg' alt='{$category_title}'
width='50' height='50'
border='0' align='middle' /> {$category_title} ";
}
?>
In case you need to add client-side dynamic features to your HTML-pages, have a look at jQuery or jQuery UI.
HTML has no such capability. You would need to generate your HTML using a programming language. Then the syntax would depend on which language you were using.
e.g. in TT:
[% IF category_id %]
<img src="[% GRAFURL %]/[% category_id %].jpg"
alt="{category_title}" width="50"
height="50" border="0" align="middle"
/> [% category_title %]
[% END %]
Use javascript for generating it client side, PHP for server side. Javascript can change things on the page and provide dynamic content after the page is sent to the client; PHP can determine the content before sending it to the user (while it can edit it afterwords, it is much more convoluted).
For example, if you wanted to add it to a tag with id "dynamic", you could use this:
<html>
<head>
<script type="text/javascript">
window.onload = function() {
var img_tag = document.createElement('img');
img_tag.src = "{GRAFURL}/{category_id}.jpg";
img_tag.alt = "{category_title}";
img_tag.width = 50;
img_tag.height = 50;
img_tag.border = 0;
img_tag.align = "middle";
document.getElementById("dynamic").appendChild(img_tag);
};
</script>
</head>
<body>
<div id="dynamic">
</div>
<body>
</html>
I thoroughly recommend learning jQuery, however, where you could do things easier and faster. Also, it is up to you to replace the values in braces with the correct values (either through PHP or javascript), I couldn't tell what you were doing.
I would simply like to know if something similar to this is possible in php somehow:
<?php
$myhtmlstring = "
?>
<table>
<tr>
<td>test</td>
</tr>
</table>
<?php
";
?>
The reason for this is I would like to be able to write the html in this nice looking format but have php trim the white space after the fact.
You can use heredoc.
You can use the alternative heredoc syntax:
$myhtmlstring = <<<EOT
<table>...</table>
EOT;
Or you can use output buffering:
<?php
ob_start();
?>
<table>...</table>
<?php
$myhtmlstring = ob_get_clean();
?>
Yes
<?php
$myhtmlstring = '
<table>
<tr>
<td>test</td>
</tr>
</table>
<?php
';
// Do what you want with the HTML in a PHP variable
// Echo the HTML from the PHP variable to make the webpage
echo $myhtmlstring;
?>
I usually use the buffer functions, like so:
<?php
$whatever = "Hey man";
// This starts the buffer, so output will no longer be written.
ob_start();
?>
<html>
<head>
<title><?php echo $whatever ?></title>
</head>
<body>
<h1><?php echo $whatever ?></h1>
<p>I like this in part because you can use variables.</p>
</body>
</html>
<?php
// Here's the magic part!
$myhtmlstring = ob_get_clean();
?>
For more information about the buffer functions, look up ob_start() on
php.net.
do you mean so?
<?php
$string = '<table border="1">
<tr>
<td> test </td>
</tr>
</table>';
echo $string;
?>
I have the following code (I formated it to more lines, but in my source code I have it in one line, because innerHTML doesn't like new lines somehow - but that isn't the problem...):
<?php
echo "
<img
src='1.png'
onclick='
document.getElementById(\"my_div\").innerHTML=\"
<img src=\\\"1.png\\\" onclick=\\\"alert(\\\\\\\"text\\\\\\\");\\\" />
\";
'
/>
";
?>
And somewhere in the body I have :
<div id="my_div"></div>
So, when I click on the image, i'll have the same image inside my_div. The problem is, that when I click on the 2nd image, javascript doesn't alert anything.
But when I change this:
alert(\\\\\\\"text\\\\\\\");
to this:
alert(MyText);
and add JavaScript variable MyText:
<script>
MyText = "text";
</script>
it now works.
I think the problem is with those nested quotes:
\\\\\\\"
(level 4). Any ideas? Thanks.
EDIT: please don't post here another methods of doing this, I'd like to know why those quotes doesn't work here..
SECOND EDIT: I need that php there, because this is only a piece of my code (in full code I need it to display images in cycle...)
If you want a quote character as data (instead of as an attribute delimiter) in HTML, you represent it as " not \"
There's nothing "dynamic" in your script - you're not inserting PHP variables, so why build that all from within a PHP echo? Simply have:
Or if you want to make it even cleaner:
<script type="text/javascript">
function addImg() {
document.getElementById('my_div').innerHTML='<img src="1.png" onclick="alert(\'text\')" />';
}
</script>
<img src="1.png" onclick="addImg()" />
refactor your JS into an external file (with a function that will do the onclick logic), and try outputting something simpler with php's echo
Use jQuery!
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.2.min.js"></script>
<div id="my_div"></div>
<img src="1.png" class="my_img" />
<img src="2.png" class="my_img" />
<img src="3.png" class="my_img" />
<script type="text/javascript">
jQuery(function() {
$('.my_img').click(function() {
$('#my_div').html($(this).clone().unbind());
alert('text');
});
});
</script>
I am new to PHP. I need to output the following JavaScript with PHP. This is my code:
<html>
<body>
<?php
echo "<script type="text/javascript">";
echo "document.write("Hello World!")";
echo "</script>";
?>
</body>
</html>
But it's showing the error:
Parse error: syntax error, unexpected T_STRING, expecting ',' or ';' in /var/www/html/workbench/person/script.php on line 4
Can anyone please help? I also need some simple tutorials on how to use PHP, HTML and JavaScript for an application.
You should escape the JavaScript string delimiters inside the PHP string. You're using double quotes for both PHP and JavaScript strings. Try like this instead:
<html>
<body>
<?php
// Here, we use single quotes for PHP and double quotes for JavaScript
echo '<script type="text/javascript">';
echo 'document.write("Hello World!")';
echo '</script>';
?>
</body>
</html>
You have to escape quotes on both JavaScript and PHP when the string delimiter are the same as the quotes:
echo "\""; // escape is done using a backslash
echo '\'';
Same in JavaScript:
alert("\""); // escape is done using a backslash
alert(echo '\'');
But because it's very hard to read a string with such escape sequences, it is better to combine single with double quotes, as needed:
echo '"';
echo "'";
The error you get if because you need to escape the quotes (like other answers said).
To avoid that, you can use an alternative syntax for you strings declarations, called "Heredoc"
With this syntax, you can declare a long string, even containing single-quotes and/or double-quotes, whithout having to escape thoses ; it will make your Javascript code easier to write, modify, and understand -- which is always a good thing.
As an example, your code could become :
$str = <<<MY_MARKER
<script type="text/javascript">
document.write("Hello World!");
</script>
MY_MARKER;
echo $str;
Note that with Heredoc syntax (as with string delimited by double-quotes), variables are interpolated.
Another option is to do like this:
<html>
<body>
<?php
//...php code...
?>
<script type="text/javascript">
document.write("Hello World!");
</script>
<?php
//....php code...
?>
</body>
</html>
and if you want to use PHP inside your JavaScript, do like this:
<html>
<body>
<?php
$text = "Hello World!";
?>
<script type="text/javascript">
document.write("<?php echo $text ?>");
</script>
<?php
//....php code...
?>
</body>
</html>
Hope this can help.
An easier way is to use the heredoc syntax of PHP. An example:
<?php
echo <<<EOF
<script type="text/javascript">
document.write("Hello World!");
</script>
EOF;
?>
You need to escape your quotes.
You can do this:
echo "<script type=\"text/javascript\">";
or this:
echo "<script type='text/javascript'>";
or this:
echo '<script type="text/javascript">';
Or just stay out of php
<script type="text/javascript">
You need to escape the double quotes like this:
echo "<script type=\"text/javascript\">";
echo "document.write(\"Hello World!\")";
echo "</script>";
or use single quotes inside the double quotes instead, like this:
echo "<script type='text/javascript'>";
echo "document.write('Hello World!')";
echo "</script>";
or the other way around, like this:
echo '<script type="text/javascript">';
echo 'document.write("Hello World!")';
echo '</script>';
Also, checkout the PHP Manual for more info on Strings.
Also, why would you want to print JavaScript using PHP? I feel like there's something wrong with your design.
The following solution should work quite well for what you are trying to do.
The JavaScript block is placed very late in the document so you don't have to
worry about elements not existing.
You are setting a PHP variable at the top of the script and outputting just
the value of the variable within the JavaScript block.
This way, you don't have to worry about escaping double-quotes or HEREDOCS
(which is the recommended method if you REALLY must go there).
Javascript Embedding Example
<div id="helloContainer"><div>
<script type="text/javascript">
document.getElementById('helloContainer').innerHTML = '<?= $greeting; ?>';
</script>
You want to do this:
<html>
<body>
<?php
print '
<script type="text/javascript">
document.write("Hello World!")
</script>
';
?>
</body>
</html>
instead you could easily do it this way :
<html>
<body>
<script type="text/javascript">
<?php
$myVar = "hello";
?>
document.write("<?php echo $myVar ?>");
</script>
</body>
You are using " instead of ' It is mixing up php syntax with javascript. PHP is going to print javascript with echo function, but it is taking the js codes as wrong php syntax. so try this,
<html>
<body>
<?php
echo "<script type='text/javascript'>";
echo "document.write('Hello World!')";
echo "</script>";
?>
</body>
</html>
<?php
echo '<script type="text/javascript">document.write(\'Hello world\');</script>';
?>
Try This:
<html>
<body>
<?php
echo "<script type="text/javascript">";
echo "document.write("Hello World!");";
echo "</script>";
?>
</body>
</html>