如何使用 Twig 从 JSON 中读取数据?
问题描述:
我有一个简单的 PHP 文件:
I have a simple PHP file:
<?php
// Load our autoloader
require_once __DIR__.'/vendor/autoload.php';
// Specify our Twig templates location
$loader = new Twig_Loader_Filesystem(__DIR__.'/views');
// Instantiate our Twig
$twig = new Twig_Environment($loader);
echo $twig->render('index.html', ['products' => $products] );
现在我为信息设置了products"数组.
and now i set the "products" array for the info.
但我会从一个 JSON 文件中获取变量,我可以在其中插入我的数组,有人知道方法吗?
But i would take variables from a JSON file where i can insert my arrays, someone knows a way?
答
获取文件内容,json_decode() 到一个变量中,像其他变量一样使用:
Fetch the file contents, json_decode() it into a variable, use it like any other variable:
$json = file_get_contents("test.json");
$products = json_decode($json);