Personal project: using while loops - php

I am new to PHP. I am trying to create a simple personal project where several coins move around the page when users refresh it from their browser. I keep on getting a weird error ().
This is what my file looks like:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Treasure Map</title>
</head>
<body style="background-image:url(Bluemap.jpg); background-repeat: no-repeat">
<?php
$numberOfCoins = rand(3, 10);
while ($numberOfCoins) {
$xPosition = rand("10", "650");
$yPosition = rand("10", "400");
print '<div style="position: absolute;';
print 'left:' . $xPosition . 'px;';
print 'top:' . $yPosition . 'px">';
print '<img src="goldCoin.png" height="50px"/>';
print '</div>';
$numberOfCoins--;
}
?>
</body>
</html>
what am I doing wrong?

The file is an HTML document, therefore it cannot run PHP code.
You need to rename it from index3.html to index3.php and also make sure you are running it on a server that runs PHP

You should save the file as .php. This just shows the code itself, which means that it is not parsed.
Apart from that, your code is slightly off too.
The variable $numberOfCoins now contains a random number between 3 and 10. If you want to iterate a random number of times, an if loop might be more convenient:
$numberOfCoins = rand(3,10);
for($i = 0; $i < $numberOfCoins; $i++)
{
}

Related

foreach function only one shows

New to PHP so don`t be mad if the question is really stupid.
i have made this code :
<!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" />
<style>
img {float: left; margin-right: 30px; margin-bottom: 10px;}
</style>
<script src="js/jquery-1.7.2.min.js"></script>
<script src="js/lightbox.js"></script>
<link href="css/lightbox.css" rel="stylesheet" />
<title>Untitled Document</title>
</head>
<body>
<?php
// specify url of xml file
$url = "http://travelplaza.ro/turcia/belek/Belek.xml" ;
// get xml file contents
$xml = simplexml_load_file($url);
// loop begins
foreach ($xml->hotel[0] as $hotel) {
echo $hotel["hotelname"];
echo "&nbsp";
echo $hotel["stars"];
echo "<p>";
echo $hotel->description . "</br>";
echo "</p>";
echo "<p>";
echo "</p>";
}
foreach ($xml->hotel[0]->images[0] as $i) {
echo '<a href="' . $i["url"] . '" rel="lightbox"><img src="' . $i["url"] . '" width="100" height="100">';
echo "</a>";
}
Above is the xml itself..of course there are many hotels.
The result that i want is to have the title, description and pictures from the feed for the first hotel , then the second one and so on.
Instead i get only the images. If i remove the atributes [0] it gives a list with al the hotels with name , description and pics. Where is my mistake? I just want to show the hotel,description and the images. Any help would be apreciated.
Thank you.
EDIT: If i want to show only hotel[45] with description and images ?
the xml looks like so :
<hotels>
<hotel hotelcode="xxx">
<description>
bla bla
</description>
<images>
<image url="http"/>
</images>
</hotel>
The above repeats and on the last one i have the end tag.
The xml file is like this:
http://travelplaza.ro/turcia/belek/Belek.xml
Since you don't post the content of that xml file we can only guess its content...
Most likely $xml->hotel is an array of hotels. However you iterate over the frist element in that, not over the list of hotels. Try this instead:
foreach($xml->hotel as $hotel)
For the images: most likely you have to place the second foreach loop addressing the images inside the first loop, since each hotel most likely can hold references to several images. So the second loop should look something like this:
foreach($hotel->images as $i)
So the final code probably is meant to be like this:
$url = "http://travelplaza.ro/turcia/belek/Belek.xml";
// get xml file contents
$xml = simplexml_load_file($url);
// loop over the hotels
foreach($xml->hotel as $hotel){
echo $hotel["hotelname"]."&nbsp".$hotel["stars"]."\n";
echo "<p>\n".$hotel->description."\n</p>\n";
// loop this hotels images
echo "<p>\n";
foreach($hotel->images as $image) {
echo '<a href="'.$image["url"].'" rel="lightbox">'."\n";
echo '<img src="'.$image["url"].'" width="100" height="100">'."\n";
echo "</a>"\n;
}
echo"</p>\n";
}
But as said: without more details we can only guess...
hotel[0] means the first hotel in the list; when you loop over that, SimpleXML assumes you want its children. In this case, each hotel has two children, one description and one images.
You want each hotel in turn, that is, all the elements called hotel so remove the [0]:
foreach($xml->hotel as $hotel)
For the images, you want to get them at the same time as the name and description, but you have two separate loops, so you don't start looking at images until you've displayed all the descriptions.
Move the image loop inside the main loop, and change it to look at whichever hotel you're currently examining. Again, you don't want the [0], but looking at the XML there are multiple image elements inside one images element, so you need this:
foreach($hotel->images->image as $i)
(The [0] in this case sort of works as well, because $hotel->images[0] is the first and only images element, and its children are the individual image elements. I think the above better shows your intention.)
try this:
<?php
$url = "http://travelplaza.ro/turcia/belek/Belek.xml";
// get xml file contents
$xml = simplexml_load_file($url);
// loop begins
foreach($xml->hotel as $hotel) {
echo <<<EOD
<div>
<p>{$hotel['hotelname']}</p>
<p>{$hotel['stars']};</p>
<p>{$hotel->description}</p>
<p>
EOD;
foreach ($hotel->images[0] as $i) {
echo <<<EOD
<p>
<img src="{$i["url"]}" width="100" height="100">'
</p>
EOD;
}
echo <<<EOD
</div>
EOD;
}
?>

Echo Page Title in PHP

The script below echos the array and its individual elements fine but when the array elements are used to set the page title by running the script after the opening head tag, I still get "untitled document" as the page title.
Further if I try echoing $title alone and placing the title tags <> before and after the php tags, the title is set as the document type definition..
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
It seems that echo sets the relevant HTML tags required before if not already set. Whats the work around ??
<?php
include 'contentStream.php' ;
$upc = $_GET['upc'];
if (isset($upc))
{
global $upc ;
$query = "SELECT * FROM tracks WHERE album_upc='$upc'";
connect();
$db = mysql_select_db("XXXXX");
$results = mysql_query($query, $connection) ;
$result = mysql_fetch_assoc($results);
$title = $result['title']." by ".$result['author'] ;
echo "<title>".$title."</title>";
unset($results);
unset($query);
mysql_close($connection) ;
}
else
{
echo "<title> MYsUPERsITe </title> " ;
}
?>
Is this being executed within the <head> element? If not it needs to be.
I am not sure what contentstream.php is but it looks like you might be running this at the wrong location in the page.
Also try changing $title to $myTitle to see if $title has been set somewhere else.
Your problem seems to be that you are trying to change the contents of the <title> tag after it has already been produced by the non-PHP section of your page. That approach does not work in a server-side environment like PHP.
One solution is to use PHP to generate the entire HTML page, store it in a variable, and just echo() it out when you're all done.
At the top of your page, I would run and parse a database query and build a $html string to echo out later. Multiple echo() statements like you have above can get ugly, and can give you issues with headers and such if you later end up adding cookies or session variables to your site:
<?php
include ("my_cool_lib.php");
$html = "<!DOCTYPE html>";
$html .= "<html><head>";
$db = connect_to_db();
$resultset = run_a_query($db);
$title = get_title($resultset);
$html .= "<title>$title</title>";
$html .= "</head><body>";
$html .= "<h1>Results</h1>";
// loop through $resultset
// $html .= track info
// end loop
$html .= "</body></html>";
echo $html;
?>
You need to set the relevent HTML tags that you're currently missing.
<html>
<head>
<title>Your title</title>
</head>
<body>
body stuff
</body>
</html>

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.

xajax expanding list query

As you'll see, I'm a newbie to all this ajax stuff but I can do a bit of php and so I plumped for xajax to take care of the javascript for me.
I've got an array with items listed in different section. I want to use this array to produce an unordered list that expands when someone clicks on a section.
I've adapted a script I found here:
Sliding Draw
My script currently looks like this:
<?php
include ("xajax_core/xajax.inc.php");
$subs = array(
"Mortice" => array("Union Deadlock 2.5", "Union Deadlock 3", "Union Sashlock 2.5", "Union Sashlock 3"),
"Cylinders" => array("30/30 Euro", "30/40 Euro", "30/50 Euro", "30/60 Euro"),
"uPVC" => array("30/92 Fullex", "35/92 Fullex", "Sash jammer")
);
function addsub($show, $key)
{
$objResponse=new xajaxResponse();
if ($show=="true") {
$objResponse->assign("list", "style.display", "block");
$objResponse->replace("$key","innerHTML","true","false");
}
else {
$objResponse->assign("list", "style.display", "none");
$objResponse->replace("$key","innerHTML","false","true");
}
return $objResponse;
}
$xajax = new xajax();
$xajax->registerFunction("addsub");
$xajax->processRequest();
?>
<!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" />
<?php $xajax->printJavascript() ?>
<title>Expand menu test</title>
<style type="text/css">
.list {display: none;}
</style>
</head>
<body>
<?php
echo "<ul>\n";
foreach ($subs as $key => $group) {
echo "<li id=\"".$key."\" onClick=\"xajax_addsub('true','$key');\">".$key."\n";
echo "<ul class=\"list\" id=\"list\">\n";
while (list($list, $each) = each($group)) {
echo "<li id=\"list\">".$each."</li>\n";
}
echo "</ul>\n</li>\n";
}
echo "</ul>";
?>
</body>
</html>
The idea is that when an element is clicked on it changes the style display to block (thus showing the rest of the list) and sets the function to 'false' so if it's clicked again it will change the display back to none and hide the list.
Needless to say it doesn't work so if someone could point out to me why I'd be eternally grateful.
Cheers,
Nick.
Solved - I sorted it by placing the lists to be shown (or hidden) into <divs> and assigning them each a unique id and setting their style as display: none.
Then I just had to make a request to set the style as block when it was clicked on.
Thanks.
I think you should look into jQuery as your default javascript library, it's used by many web professionals and is very good. There you will find the Accordion control, which I think will suite this need very well.
Good luck!

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