简体   繁体   English

如何从外部 JavaScript 检索 PHP 中的内容

[英]How to retrieve content in PHP from external JavaScript

I have an external JavaScript file, I would like to display array content in my PHP page.我有一个外部 JavaScript 文件,我想在我的 PHP 页面中显示数组内容。 How can I display the content by loop.如何循环显示内容。 I tried to display the content using following code.我尝试使用以下代码显示内容。 But Failed.但失败了。

 <?php
 ini_set('allow_url_fopen', 'On');

$feed = file_get_contents("https://example.com/media-list.js");
$array = json_decode($json);
var_dump($array);
$urlPoster=array();
foreach ($array as $value) { 
    $urlPoster[]=$value->urlPoster;
}
print_r($urlPoster);
 ?>

media-list.js content media-list.js 内容

var contents = {
    "0W7EHsR8":{
        "attachmentCode":"0W7EHsR8",
        "title":"title1",

    },  

    "vciym7Zb4":{
        "attachmentCode":"vciym7Zb4",
        "title":"title2",

    },  

    "XlKBM6":{
        "attachmentCode":"XlKBM6",
        "title":"Title3",

    }
};

I would like to display content like我想显示类似的内容

Title is "title1".标题是“title1”。

Title is "title2".标题是“title2”。

You are trying to use json_decode() on a Javascript Array.您正在尝试在 Javascript 阵列上使用json_decode() JSON and Javascript are two different things. JSON 和 Javascript 是两个不同的东西。
You need to convert your contents array to JSON, save it in a different file ( contents.json for example) and load that file with file_get_contents .您需要将您的contents数组转换为contents.json ,将其保存在不同的文件中(例如 content.json)并使用file_get_contents加载该文件。
If you need to do this only once you can do something like如果你只需要这样做一次,你可以做类似的事情

var contents = {
    "0W7EHsR8":{
        "attachmentCode":"0W7EHsR8",
        "title":"title1",

    },  

    "vciym7Zb4":{
        "attachmentCode":"vciym7Zb4",
        "title":"title2",

    },  

    "XlKBM6":{
        "attachmentCode":"XlKBM6",
        "title":"Title3",

    }
};

console.log(JSON.stringify(contents));

and copy the result from the console (click CTRL+Shift+I to open it).并从控制台复制结果(单击 CTRL+Shift+I 打开它)。

JSON.stringify() takes a Javascript array and turns it into a JSON string. JSON.stringify()采用 Javascript 数组并将其转换为 JSON 字符串。

for this small array the JSON equivalent is对于这个小阵列,等效的 JSON 是

{"0W7EHsR8":{"attachmentCode":"0W7EHsR8","title":"title1"},"vciym7Zb4":{"attachmentCode":"vciym7Zb4","title":"title2"},"XlKBM6":{"attachmentCode":"XlKBM6","title":"Title3"}}

If you intend on making this dynamic (say, loading all attachemnts from a database) you can create a php file that loads that data into an array and returns it into proper JSON using json_encode().如果您打算使这种动态化(例如,从数据库加载所有附件),您可以创建一个 php 文件,该文件将该数据加载到一个数组中,并使用 json_encode() 将其返回到正确的 JSON 中。 Loading that file with file_get_contents and using json_decode like you are doing now should do the trick.使用 file_get_contents 加载该文件并像现在一样使用 json_decode 应该可以解决问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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