i'm doing a training in PHP, i'm still learning, and i'm trying to make a "poor video-game advertise", i got my php file in a folder, and a folder named "img" inside the same folder. Well, all i want to know is hows do i make to show a different image for a different game ? I'm trying to at least show Watch_Dogs img, but it isn't showing as well... And i need to show the correct image for the correct game, can anyone help me out ? here's the code, it's pretty poor i know...:
<!Doctype HTML>
<html lang="pt-br">
<head>
<title> Repetição em PHP </title>
</head>
<body>
<?php
$arrayGames = array("Watch_Dogs " => " R$199,90",
"Dead Space " => " R$149,90",
"Wolfenstein " => " R$189,90");
foreach($arrayGames as $titulo => $preco){
echo"<p>Jogo: " . $titulo . "<img src='img/watch_dogs.jpg' /> </p>" . $preco;
}
?>
</body>
</html>
<?php
$arrayGames = array("Watch_Dogs " => array(" R$199,90","watch_dogs.jpg"),
"Dead Space " => array("R$149,90","dead_space.jpg"),
"Wolfenstein " => array("R$189,90","wolfenstein.jpg")
);
foreach($arrayGames as $titulo => $preco){
echo"<p>Jogo: " . $titulo . "<img src='img/{$preco[1]}' /> </p>" . $preco[0];
}
?>
The image you are showing must be relative to your php file location.
Ex:
CURRENT_FOLDER
|_ file.php
|_ <img>
|_ watch_dog.jpg
|_ ... .jpg
You could store the data on your array as multi-dimenional:
$games = array("Watch_Dogs " => array("price"=>" R$199,90","img"=>"http://placehold.it/350x150"),
"Dead Space " => array("price"=>" R$199,90","img"=>"http://placehold.it/350x150"),
"Wolfenstien " => array("price"=>" R$199,90","img"=>"http://placehold.it/350x150")
);
$html = '';
foreach($games as $game_title =>$price_img)
{
$html .= "<p>Jogo: {$game_title} <img src='{$price_img['img']}' /> {$price_img['price']} </p>";
}
echo $html;
DEMO
You need to derive the leading part of the file name from the array key. And you need to remove the trailing spaces on the key names before appending the .jpg.
In my suggested solution, I've elected to modify the key to remove the trailing space; if the trailing space is important, you'll need to rtrim the key before using it.
<!Doctype HTML>
<html lang="pt-br">
<head>
<title> Repetição em PHP </title>
</head>
<body>
<?php
$arrayGames = array("Watch_Dogs" => " R$199,90",
"Dead Space" => " R$149,90",
"Wolfenstein" => " R$189,90");
foreach($arrayGames as $titulo => $preco ) {
echo"<p>Jogo: " . $titulo . "<img src='img/" . $titulo . ".jpg'/> </p>" . $preco;
}
?>
</body>
</html>
Related
I'm creating a web app where I want to include JavaScript files with all file sources in an array, but I can't do that.
Header.php
<head>
<?php
$import_scripts = array(
'file01.js',
'file02.js'
);
foreach ($import_scripts as $script) {
echo '<script src="' . $script . '"></script>';
}
?>
</head>
<body>
Index.php
<?php
include('header.php');
array_push($import_scripts,'file03.js')
?>
But this only includes file01.js and file02.js, JavaScript files.
Your issue is that you've already echo'ed the scripts in headers.php by the time you push the new value into the array in index.php. So you need to add to extra scripts before you include headers.php. Here's one way to do it (using the null coalescing operator to prevent errors when $extra_scripts is not set):
header.php
<?php
$import_scripts = array_merge(array(
'file01.js',
'file02.js'
), $extra_scripts ?? []);
?>
<!DOCTYPE html>
<html>
<head>
<!-- Scripts Section -->
<?php
foreach ($import_scripts as $script) {
echo '<script src="' . $script . '"></script>' . PHP_EOL;
}
?><title>Demo</title>
</head>
<body>
<p>Blog</p>
index.php
<?php
$extra_scripts = ['file03.js'];
include 'header.php';
?>
Output (demo on 3v4l.org)
<!DOCTYPE html>
<html>
<head>
<!-- Scripts Section -->
<script src="file01.js"></script>
<script src="file02.js"></script>
<script src="file03.js"></script>
<title>Demo</title>
</head>
<body>
<p>Blog</p>
header.php
<?php
function scripts()
{
return [
'file01.js',
'file02.js'
];
}
function render($scripts)
{
foreach ($scripts as $script) {
echo '<script src="' . $script . '"></script>';
}
}
?>
<head>
index.php:
<?php
include 'header.php';
$extra_scripts = scripts();
$extra_scripts[] = 'script3.js';
render($extra_scripts);
?>
</head>
<body>
PHP is processed top down so it will currently be adding file03.js to the array after the foreach has been run.
This means you have two options:
Run the scripts after the header (Not reccomended)
Like Nick suggested, in index.php, specify additional scripts before the header is called
Other answers have answered why (you output content before adding the item to the array).
The best solution is to do all your processing before your output. Also helps with error trapping, error reporting, debugging, access control, redirect control, handling posts... as well as changes like this.
Solution 1: Use a template engine.
This may be more complex than you need, and/or add bloat. I use Twig, have used Smarty (but their site is now filled with Casino ads, so that's a concern), or others built into frameworks. Google "PHP Template engine" for examples.
Solution 2: Create yourself a quick class that does the output. Here's a rough, (untested - you will need to debug it and expand it) example.
class Page
{
private string $title = 'PageTitle';
private array $importScripts = [];
private string $bodyContent = '';
public setTitle(string $title): void
{
$this->title = $title;
}
public addImportScript(string $importScript): void
{
$this->importScripts[] = $importScript;
}
public addContent(string $htmlSafeBodyContent): void
{
$this->bodyContent .= $bodyContent;
}
public out(): void
{
echo '<!DOCTYPE html>
<html>
<head>
<!-- Scripts Section -->
';
foreach ($this->importScripts as $script) {
echo '<script src="' . htmlspecialchars($script) . '"></script>' . PHP_EOL;
}
echo '
<!-- End Scripts Section -->
<title>' . htmlspecialchars($this->title) . '</title>
</head>
<body> . $this->bodyContent . '
</body>
</html>';
exit();
}
}
// Usage
$page = new page();
$page->setTitle('My Page Title'); // Optional
$page->addImportScript('script1');
$page->addImportScript('script2');
$page->addContent('<h1>Welcome</h1>');
// Do your processing here
$page->addContent('<div>Here are the results</div>');
$page->addImportScript('script3');
// Output
$page->out();
I'd create a new php file, say functions.php and add the following code into it.
<?php
// script common for all pages.
$pageScripts = [
'common_1.js',
'common_2.js',
];
function addScripts(array $scripts = []) {
global $pageScripts;
if (!empty ($scripts)) { // if there are new scripts to be added, add it to the array.
$pageScripts = array_merge($pageScripts, $scripts);
}
return;
}
function jsScripts() {
global $pageScripts;
$scriptPath = './scripts/'; // assume all scripts are saved in the `scripts` directory.
foreach ($pageScripts as $script) {
// to make sure correct path is used
if (stripos($script, $scriptPath) !== 0) {
$script = $scriptPath . ltrim($script, '/');
}
echo '<script src="' . $script .'" type="text/javascript">' . PHP_EOL;
}
return;
}
Then change your header.php as
<?php
include_once './functions.php';
// REST of your `header.php`
// insert your script files where you needed.
jsScripts();
// REST of your `header.php`
Now, you can use this in different pages like
E.g. page_1.php
<?php
include_once './functions.php';
addScripts([
'page_1_custom.js',
'page_1_custom_2.js',
]);
// include the header
include_once('./header.php');
page_2.php
<?php
include_once './functions.php';
addScripts([
'./scripts/page_2_custom.js',
'./scripts/page_2_custom_2.js',
]);
// include the header
include_once('./header.php');
You are adding 'file03.js' to $import_scripts after including 'header.php', so echoing scripts it have been done yet. That's why 'file03.js' is not invoked.
So, you need to add 'file03.js' to $import_scripts before echoing scripts, this means before include 'header.php'.
A nice way is to move $import_scripts definition to index.php, and add 'file03.js' before including 'header.php'.
But it seems that you want to invoke certain JS scripts always, and add some more in some pages. In this case, a good idea is to define $import_scripts in a PHP file we can call init.php.
This solution will be as shown:
header.php
<head>
<?php
foreach ($import_scripts as $script) {
echo '<script src="' . $script . '"></script>';
}
?>
</head>
<body>
init.php
<?php
$import_scripts = array(
'file01.js',
'file02.js'
);
index.php
<?php
require 'init.php';
array_push($import_scripts,'file03.js');
include 'header.php';
header.php
<?php
echo "<head>";
$importScripts = ['file01.js','file02.js'];
foreach ($importScripts as $script) {
echo '<script src="' . $script . '"></script>';
}
echo "</head>";
echo "<body>";
index.php
<?php
include 'header.php';
array_push($importScripts, 'file03.js');
print_r($importScripts);
Output
Array ( [0] => file01.js [1] => file02.js [2] => file03.js )
I've been using simplexml_load_file to parse a XML URL, however, the file size is above 100mb and instead of loading only the nodes, what's happening is that the script is loading the whole XML file before the nodes are extracted and parsed, what is resulting in a page TimeOut.
I'm using the following code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Boutique</title>
</head>
<body>
<?php header ('Content-type: text/html; charset=UTF-8'); ?>
<!-- --><link rel="stylesheet" href="/va/artigos-complexos/afilio/afilio-vitrine.css" type="text/css" />
<div><p class="ofertasdotopovitrine">Conheça nossas super ofertas!</p>
</div>
<div class="mainproductebayfloatright-bottom">
<?php
function parse($url, $offset = 1, $limit = -1)
{
$xml = simplexml_load_file($url);
$limitCriteria = '';
if ($limit > 0) {
$limitCriteria = 'and position() <= ' . ((int)$offset + (int)$limit + 1);
}
$products = array();
$path = sprintf('//produto[position() >= %s %s]', (int)$offset, $limitCriteria);
foreach($xml->xpath($path) as $product) {
$products[] = array(
'nome' => $product->nome,
'preco_promocao' => $product->preco_promocao,
'description' => $product->descricao,
'link_imagem' => $product->link_imagem,
'link_produto' => $product->link_produto,
'preco_normal' => $product->preco_normal,
'parcelas' => $product->parcelas,
'vl_parcelas' => $product->vl_parcelas
);
}
return $products;
}
//XML GOES HERE
$products = parse('http://v2.afilio.com.br/aff/aff_get_boutique.php?boutiqueid=37930-895987&token=53e355b0a09ea0.74300807&progid=1010&format=XML', 5, 5);
?>
<?php
foreach ($products as $product) {
print '<div class="aroundebay"><div id="aroundebay2">';
/* */
print '<div class="titleebay"><a target="_blank" rel="nofollow" href="'. $product['link_produto'] . '">' . $product['nome'] . '"</a></div>';
print '<div class="mainproduct"><a target="_blank" rel="nofollow" href="' . $product['link_produto'] . '"><img style="height:120px" src="' . $product['link_imagem'] . '"/><br/>';
//print "De:; R$". $preco_normal . "<br/>";
print '<span>Apenas R$' . $product['preco_promocao'] . '<br/></a></span></div>';
//print "Em " . $parcelas . "x de : R$" . $vl_parcelas . "</a></span></div>";
print '</div></div>';
}
?>
</div>
</body>
</html>
The CSS is irrelevant.
The script works just fine when you use a smaller XML, such as this one:
http://v2.afilio.com.br/aff/aff_get_boutique.php?boutiqueid=37930-895835&token=53e355b0a09ea0.74300807&progid=1681&format=XML
Would it be possible to load only the, for exemplo, 10 first nodes of the xml without having to load the whole file first?
I'm also accepting suggestions in other languages, such as jQuery.
Thanks in advance. You can also change the file format to JSON and RSS, just change format=XML to format=JSON or format=RSS.
I'm trying to write a basic example of php that I want to be viewed on my website. In other words I want the following code to be viewable but I would also like a copy of it to be executable on the webpage:
<body>
<p>
<?php
$food = array("Bananas", "Toast", "Eggs", "Bacon");
echo "I like " . $food[0] . ", " . $food[1] .
" and " . $food[2] . " and " . $food[3] . ".";
?>
</p>
</body>
<?php and ?> makes code inside to execute, use <?php and ?>
I need help in displaying my images from the directory images on my public_html directory. It's been uploaded, but it doesn't appear when I run the below php script. Please does anyone know why?
<?php
include_once("connect.php");
?>
<!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>Untitled Document</title>
</head>
<body>
<?php
//Retrieves data from MySQL
$data = mysql_query("SELECT * FROM authors") or die(mysql_error());
//Puts it into an array
while($info = mysql_fetch_array( $data ))
{
Echo "<img src=http://giveaway.comli.com/public_html/images/".$info['photo']."> <br>";
Echo "<b>Name:</b> ".$info['name'] . "<br> ";
Echo "<b>Title:</b> ".$info['title'] . " <br>";
Echo "<b>Phone:</b> ".$info['description'] . " <br>";
Echo "<b>Link<br>";
Echo "<b>Country:</b> ".$info['country'] . " <hr>";
}
?>
</body>
</html>
Is your public_html directory really not your site's document root? Perhaps you mean to say:
Echo "<img src=http://giveaway.comli.com/images/".$info['photo']."> <br>";
Where /images is a directory at the site document root. In a typical hosting situation, public_html would be the site document root, meaning that referenced from the web (rather than the file system), it is /.
What is the document root of your site? I'm guessing it's /home/.../public_html, which means the URL to access the images would really be http://giveaway.comli.com/images. Absolute urls of the sort you're using are really only necessary if you're using multiple different hosts/servers for your site, and/or are intending for the html to be portable. You could probably get away with using just <img src="/images/...">.
As I can see your document roo directory is public_html, so URL path to your photo will be look like this $image_url = "/images/" . $info['photo'];
I have an upload script that write a index.html file, I modified it to mail me the results, however the point to the root, since the email isn't in the root, the image doesn't load.
How do I append the code to add "http://www.home.html/uploaded" prior to the ". $value ." so that the images show up in the email.
Here is portion of PHP that assigns the images to a $result:
// Process value of Imagedata field, this is JPEG-files array
foreach ($_FILES[Imagedata][name] as $key => $value)
{
$uploadfile = $destination_dir . basename($_FILES[Imagedata][name][$key]);
if (move_uploaded_file($_FILES['Imagedata']['tmp_name'][$key], $uploadfile))
{
$result .= "File uploaded: <a href='". $value . "'>" . $value . "</a><br>";
}
}
//
$result .= "<br>";
Here is what I'm now receiving in the email, :
<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Upload results</title>
</head>
<body>
AdditionalStringVariable: pass additional data here<br><a>
href='gallery_grannylovesthis_l.jpg'><img border = '0'
src='QIU_thumb_gallery_grannylovesthis_l.jpg'/></a><br><br><br>File uploaded: <a
href='gallery_grannylovesthis_l.jpg'>gallery_grannylovesthis_l.jpg</a><br><br>
GlobalControlData:
PHOTO_VISIBILITY : 2<br>
GlobalControlData:
PHOTO_DESCR : Requiredtest<br>
GlobalControlData:
PHOTO_TITLE : Requiredtest<br><br>gallery_grannylovesthis_l.png<br> control: , value: <br>
</body>
</html>
Thanks in advance for any guidance...I have a feeling it's something simple.
Like this:
<a href='http://www.home.html/uploaded/". $value . "'>"
Your code has a malformed tag:
<a>
href='gallery_grannylovesthis_l.jpg'><img border = '0'
It should be like this:
<a href='gallery_grannylovesthis_l.jpg'><img border = '0'
Notice on yours you have href (you added a > when there should not be one)