Készítsünk egy mock objektumot product néven, majd rendereljünk HTML oldalt.
<table> <thead> <th>#</th> <th>Név</th> <th>Ár</th> </thead> <tbody>{{ tableBody }}</tbody> </table>
<?php $products = [ [ "id"=>1, "name"=>"vaj", "price"=>1.8 ], [ "id"=>2, "name"=>"kenyér", "price"=>0.8 ], [ "id"=>3, "name"=>"tej", "price"=>0.9 ] ]; $table = file_get_contents('templates/table.html'); $rows = ''; foreach($products as $product) { $tr = file_get_contents('templates/tr.html'); $tr = str_replace('{{ id }}', $product['id'], $tr); $tr = str_replace('{{ name }}', $product['name'], $tr); $tr = str_replace('{{ price }}', $product['price'], $tr); $rows .= $tr; } echo str_replace('{{ tableBody }}', $rows, $table);
<!DOCTYPE html> <html lang="hu"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>PHP</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script> </head> <body> <div class="container"> <h1>Áru</h1>
</div> </body> </html>
<?php $products = [ [ "id"=>1, "name"=>"vaj", "price"=>1.8 ], [ "id"=>2, "name"=>"kenyér", "price"=>0.8 ], [ "id"=>3, "name"=>"tej", "price"=>0.9 ] ];
<?php include_once('includes/database.php'); echo file_get_contents('templates/head.html'); $home = file_get_contents('templates/home.html'); $rows = ''; foreach($products as $product) { $tr = file_get_contents('templates/tr.html'); $tr = str_replace('{{ id }}', $product['id'], $tr); $tr = str_replace('{{ name }}', $product['name'], $tr); $tr = str_replace('{{ price }}', $product['price'], $tr); $rows .= $tr; } echo str_replace('{{ tableBody }}', $rows, $home); echo file_get_contents('templates/foot.html');
Meg kell szereznünk az adatokat azon weblapon, ahol használni szeretnénk.
Legyártjuk az adatokat:
<?php $products = [ [ "id"=>1, "name"=>"vaj", "price"=>1.8 ], [ "id"=>2, "name"=>"kenyér", "price"=>0.8 ], [ "id"=>3, "name"=>"tej", "price"=>0.9 ] ];
Befoglaljuk az adatokat tartalmazó állományt, majd egy JavaScript változóba tesszük:
<?php include_once('includes/database.php'); ?> <!DOCTYPE html> <html lang="hu"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>PHP tömb JavaScript számára</h1> <script> var products = <?php echo json_encode($products); ?>; </script> <script src="app.js"></script> </body> </html>
Máris látjuk az app.js JavaScript kódban:
console.log(products);