简体   繁体   中英

Use PHP to extract data from an object literal in the middle of a JavaScript program

I have a JS file with the following assignment of an object literal to a variable in it.

var data = {
  title:"My webpage",
};

I want to access this JS file from PHP to read this data so I can output it into HTML.

Since this is not JSON, the following does not work.

$str = file_get_contents("data/data.js");
$object = json_decode($str, true);
echo $object['title'];

How would I access that file and write out the 'title' to HTML using a PHP file?

Is there a reason you can't use a .json file?

If not a really quick and easy/dirty solution would be to have a file like:

data.json

{
  "title":"My webpage"
}

And then just get it the way you are trying to.

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