简体   繁体   中英

How can I use php to populate a manifest.json file?

I have a manifest.json file that loads correctly when placed in the root directory of my wesite. Instead of it being a static file, I would like to use php variables from within my site to populate the values inside of the manifest.

I can't find any information on this in the spec , and I'm not sure if it's possible.

I've tried switching the name of my manifest to manifest.php and used header('Content-Type: application/json') within it.

Inside my index file head:

<script src="<?php echo $SITE_URL;?>/main.js"></script>
<script src="<?php echo $SITE_URL;?>/sw.js"></script>
<link rel="manifest" href="<?php echo $SITE_URL;?>/manifest.php">

Inside my manifest.php:

<?php header('Content-Type: application/json');
echo "
{
  \"name\": \"$SiteName\",
  \"gcm_user_visible_only\": true,
  \"short_name\": \"$Name\",
  \"description\": \"$PageDescription.\",
  \"start_url\": \"/index.php\",
  \"display\": \"standalone\",
  \"orientation\": \"portrait\",
  \"background_color\": \"$darkblue\",
  \"theme_color\": \"#f0f0f0\",
  \"icons\": [{
    \"src\": \"logo-load.png\",
    \"sizes\": \"96x96 128x128 144x144\",
    \"type\": \"image/png\"
  },{
    \"src\": \"logo-icon.png\",
    \"sizes\": \"48x48 72x72\",
    \"type\": \"image/png\"     
  }]
}
";
?>

The variables $SiteName, $Name, $PageDescription, $darkblue, etc are all defined within my document head before the manifest.php is loaded.

Is what I'm trying possible?

Main question I have is where are these constants pulled from? Sometimes people set them at the server host level and import them ( environment variables ). Another option (sort of blurs with what you are doing) is to parse an INI file .

I would do something like the following:

<?php

$siteName = 'foo';
$name = 'bar';
$pageDescription = 'baz';

$manifest = [
    "name" => $siteName,
    "gcm_user_visible_only" => true,
    "short_name" => $name,
    "description" => $pageDescription,
    "start_url" => "/index.php",
    "display" => "standalone",
    "orientation" => "portrait",
    "background_color" => $darkblue,
    "theme_color" => "#f0f0f0",
    "icons" => [
        "src" => "logo-load.png",
        "sizes"=> "96x96 128x128 144x144",
        "type" => "image/png"
    ],
    "src" => "logo-icon.png",
    "sizes" => "48x48 72x72",
    "type" => "image/png"
];

header('Content-Type: application/json');
echo json_encode($manifest);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM