Problem echoing php string as javascript function - php

I'm using Jaipho to display images to a mobile gallery from a custom Wordpress plugin. The wordpress theme that uses the Jaipho gallery is displayed using the WP-mobile-detector plugin.
The problem I am having is when I use php to gather the URLs to the photos to echo out a function to be parsed by javascript. I took the resulting static javascript code from the element inspector of Safari and pasted it into my code, commenting out the php, and it works everywhere. Safari for iOS doesn't seem to like the javascript code generated by the php.
HTML 5
<DOCTYPE html>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;"/>
PHP 5.2.6
Wordpress 3.2.1
When it works:
User Agent set to iPhone on Safari
Static code replaces php-generated code
$imageArray = $case->images_assc_array();
$i = 0;
foreach($imageArray['views'] as $view_name => $view_images) {
$before_img = $view_images['before'];
$after_img = $view_images['after'];
echo "dao.ReadImage($i,'".$before_img->medium_size()."','".$before_img->small_size()."','".ucfirst($view_name)." Before','".$case->description."');";
$i++;
echo "dao.ReadImage($i,'".$after_img->medium_size()."','".$after_img->small_size()."','".ucfirst($view_name)." After','".$case->description."');";
$i++;
}
Expected example generated output:
dao.ReadImage( 0,'/wp-content/uploads/rmgallery_images/medium/408/before-front.jpg','/wp-content/uploads/rmgallery_images/small/408/before-front.jpg','Front Before','38 year old who underwent a tummy tuck.');
dao.ReadImage( 1,'/wp-content/uploads/rmgallery_images/medium/410/after-front.jpg','/wp-content/uploads/rmgallery_images/small/410/after-front.jpg','Front After','38 year old who underwent a tummy tuck.');
dao.ReadImage( 2,'/wp-content/uploads/rmgallery_images/medium/409/before-side.jpg','/wp-content/uploads/rmgallery_images/small/409/before-side.jpg','Side Before','38 year old who underwent a tummy tuck.');
dao.ReadImage( 3,'/wp-content/uploads/rmgallery_images/medium/411/after-side.jpg','/wp-content/uploads/rmgallery_images/small/411/after-side.jpg','Side After','38 year old who underwent a tummy tuck.');

You have some mismatched quotes:
echo dao.ReadImage($i,'".$before...
echo "dao.ReadImage($i,'".$after...
and so on.
Try these:
echo 'dao.ReadImage('.$i.',"'.$before_img->medium_size().'","'.$before_img->small_size().'","'.ucfirst($view_name).' Before","'.$case->description.'");';
echo 'dao.ReadImage('.$i.',"'.$after_img->medium_size().'","'.$after_img->small_size().'","'.ucfirst($view_name).' After","'.$case->description.'");';

Credit to #Marc B and #linuxrules94 for a combined solution:
<?php
$imageArray = $case->images_assc_array();
$i = 0;
foreach($imageArray['views'] as $view_name => $view_images):
$before_img = $view_images['before'];
$after_img = $view_images['after'];
?>
dao.ReadImage(<?=json_encode($i);?>, <?=json_encode($before_img->medium_size());?>,<?=json_encode($before_img->small_size());?>,<?=json_encode(ucfirst($view_name));?> + " Before", <?=json_encode(stripslashes($case->description));?>);
<? $i++; ?>
dao.ReadImage(<?=json_encode($i);?>, <?=json_encode($after_img->medium_size());?>,<?=json_encode($after_img->small_size());?>,<?=json_encode(ucfirst($view_name));?> + " After", <?=json_encode(stripslashes($case->description));?>);
<? $i++;
endforeach; ?>
Thanks, everyone!

How about using heredocs: http://php.net/manual/en/language.types.string.php

Related

print_r causes page to refresh?

This is very bizarre and I have spent quite a while trying to figure out why the pages I was testing kept refreshing when they weren't supposed to. I finally narrowed it down to when I deleted the print_r($_SESSION['boosters']) code it quit refreshing. When the print_r is there it refreshes. You can test this yourself at http://prayerpond.com/posttest2.php (just keep manually refreshing the page and look at the counter).
Take a look at the counter displayed at the beginning of the page. If it skips a number then it is refreshing the page once it gets to the print_r.
Here's the code for the counter at the beginning of the page:
$_SESSION['counter']++;
echo $_SESSION['counter'];
Here's the rest of the code (I deleted everything else that was unnecessary to recreate the problem):
<?php
require_once($_SERVER['DOCUMENT_ROOT'] . "/start.php");
// PRE-HEADER PROCESSING
unset($_SESSION['boosters']);
$_SESSION['counter']++;
echo $_SESSION['counter'];
$sql = "SELECT prayers_views_likes.*, prayers.postid, prayers.privacy, prayers.username
FROM prayers_views_likes
LEFT JOIN prayers ON prayers_views_likes.postid = prayers.postid
WHERE prayers_views_likes.type = 'answer'
and prayers.privacy != 'hidden'
and prayers.username != 'hoodleehoo'
and prayers_views_likes.adj_ratio > 0
ORDER BY prayers_views_likes.adj_ratio DESC, prayers_views_likes.views DESC
";
$_SESSION['boosters'] = send_query($sql);
print_r ($_SESSION['boosters']); //DELETE
// END PRE-HEADER PROCESSING
?>
<!doctype html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://ogp.me/ns/fb#">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta charset="utf-8">
</head>
<body>
</body>
</html>
This is driving me NUTS! Anyone know what on earth is causing this?
Try doing:
echo '<pre>' . htmlentities(print_r($_SESSION['boosters'], true)) . '</pre>';
Giving a true second argument to print_r() makes it return the formatted string instead of outputting it directly. Then htmlentities() will encode any HTML syntax in the result -- there's probably some HTML or Javascript that's causing the refresh. I also put it inside <pre> so that the formatting will be retained.

Getting title of page with php is not UTF-8

I used many types of code to get a title of one url address with php, but with all of them, i had problem,
For example,the below code , using DOMDocument :
$doc = new DOMDocument();
#$doc->loadHTML(file_get_contents("http://www.farsnews.com/newstext.php?nn=13930431001635"));
// find the title
$titlelist = $doc->getElementsByTagName("title");
if($titlelist->length > 0){
echo $titlelist->item(0)->nodeValue;
}
The out put of the code , is this :
طبق اعلام مهدی تاج گران‌ترین بازیکن ÙÂوتبال ایران معرÙÂی شد
But the title of that page is this :
طبق اعلام مهدی تاج گران‌ترین بازیکن فوتبال ایران معرفی شد
So, the problem is with encoding of the string . May be the problem is just with this site !
But how ti fix this ? And echo out the correct title ?
edit:
i have tested this meta :
<META http-equiv="Content-Type" content="text/html; charset=utf-8">
But no results.
Did you check if you php internal encoding handle UTF-8 correctly?
<?php
var_dump(mb_internal_encoding());
?>

Show variable in meta tag

I have a div which is like this:
<div id="beskrivelse" class="description html_content" itemprop="description">
{{description}}
</div>
The content {{description}} is made in the backend.
How can I make it so that this content will be shown in my meta here:
<meta property="og:description" content=" HERE "/>
I get a syntax error if I write:
<meta property="og:description" content=" {{description}} "/>
Is ther a simple way to do it? Maybe put it in a variable of some sort?
There is no way for me to change this in the backend as I am using a closed system.
I want what I have written in my {{description}} to be shown in the meta tag.
Any suggestions?
Using JavaScript you can achieve this.
<script language="javascript">
var descval = document.getElementById('beskrivelse').innerHTML;
var paras = document.getElementsByTagName('meta');
for (i = 0; i < paras.length; i++) {
var test = paras[i].getAttribute('property');
if(test == "og:description")
{
paras[i].content = descval;
}
}
</script>
Fiddle Demo
Using Devloper Tool you can check the meta tag new content.

How to echo an PHP tag?

I'm trying to echo a PHP tag by doing this:
echo "<?php echo \"test\"; ?>";
The result should be just "test" without quotes, but my code isn't working. What is happening is that nothing is shown on the page, but the source code is "<?php echo "teste"; ?>"
Most of you will want to know why I want to do this. I'm trying to make my own template system; the simplest way is just using file_get_contents and replacing what I want with str_replace and then using echo.
The problem is, that in the template file, I have to have some PHP functions that doesn't work when I echo the page, is there another simple way to do this? Or if you just answer my question will help a lot!
Here is an example of what I am trying to accomplish:
template.tpl:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>[__TITULO__]</title>
</head>
<body >
<p>Nome: [__NOME__] <br />
Email: [__EMAIL__]<br />
<?php
if ($cidade != "") {?>
Cidade: [__CIDADE__]<br />
<?php
}
?>
Telefone: ([__DDD__]) [__TELEFONE__] <br />
Fax:
([__DDDFAX__]) [__FAX__] <br />
Interesse: [__INTERESSE__]<br />
Mensagem:
[__MENSAGEM__] </p>
</body>
</html>
index.php
<?php
$cidade = "Teste";
$file = file_get_contents('template.php');
$file = str_replace("[__TITULO__]","Esse Título é téste!", $file);
$file = str_replace("[__NOME__]","Cárlos", $file);
$file = str_replace("[__EMAIL__]","moura.kadu#gmail.com", $file);
if ($cidade != "") {
$file = str_replace("[__CIDADE__]",$cidade, $file);
}
echo $file;
?>
I can solve all this just not showing the div that has no content. like if i have a template, and in it i have 2 divs:
<div id="content1">[__content1__]</div>
<div id="content2">[__content2__]</div>
if the time that i set the content to replace the template I set the content1 and not set content 2 the div content2 will not show...
Use htmlspecialchars
That will convert the < > to < and >
You are dealing with two sets of source code here that should never be confused - the server code (PHP, which is whatever is in the <?php ?> tags) and the client (or browser) code which includes all HTML tags. The output of the server code is itself code that gets sent to the browser. Here you are in fact successfully echoing a PHP tag, but it is meaningless to the browser, which is why the browser ignores it and doesn't show anything unless you look at the client code that got sent to it.
To implement templates in this style, either they should not have any PHP code, or the resulting string (which you have stored in $file) should itself be executed as though it were PHP, rather than echoing it straight to the client. There are various ways to do this. One is to parse out the PHP tags in the string, echo everything that is not within the PHP tags and run eval() on everything that is.

How to Count number of lines of javascript in php files?

I need to count the no. of lines of inline java script between script tags in php files. How do I do it? Will grep linux command suffice or I can get some tool to do it? Please help.
You might use a regular expression like to extract the content of each SCRIPT tag in your files and than count the \n occurrences within the content.
This regex should match all script tag including the opening and closing tag:
/<script[^>]*?>(.*)?</script>/sm
You should than remove the tags and lines without any code to count the real lines of JavaScript code.
Please take a look on the following code,it works but you may need to updates as per your requirements
<?php
$file = file('thisfile.php');
for($i=0;$i<count($file);$i++)
{
if(trim($file[$i]) == "<script language=\"javascript\">")
{
$start = $i.'<br>';
}
if(trim($file[$i]) == "</script>")
{
$end = $i.'<br>';
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script language="javascript">
var a = 10;
var b = 10;
var c = 10;
var d = 10;
var e = 10;
var e = 10;
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<?php echo ($end - $start)-1; ?>
</body>
</html>
save this php file as thisfile.php then try
Have a nice day
If you need to do this from a processed HTML page, use DOM to get all script tags without a src attribute. Then for each found node split the child TextNode by the linebreak or simple count them. Done.
If you need to grab this from actual PHP source code, use the Tokenizer to find T_STRINGS and similar parser tokens and analyze them for <script> blocks, but note that it might be impossible to find them all, if there is code like:
echo '<' . $scriptTag . '>' . $code . '</' . $scriptTag . '>';
because that wont be analyzable as a JavaScript String before PHP processed it.

Categories