Home > Backend Development > PHP Tutorial > What are the methods for php to read local json files?

What are the methods for php to read local json files?

php中世界最好的语言
Release: 2023-03-26 15:28:01
Original
3811 people have browsed it

This time I will bring you the methods of reading local json files in php, and the precautions for reading local json files in php. The following is a practical case, let's take a look.

1.data.json file

{
	"goods":[
		{
			"type":1,
			"name":"wow精选",
			"product":[
				{
					"id":98,
					"name":"真皮大衣",
					"title":"单桶原酿酒 威士忌 新春礼盒 限量独家",
					"titleDesc":"苏格兰麦芽糖,中国定制版",
					"price":1298.00
				},
				{
					"id":99,
					"name":"品牌内衣",
					"title":"单桶原酿酒 威士忌 新春礼盒 限量独家222",
					"titleDesc":"苏格兰麦芽糖,中国定制版222",
					"price":1298.00
				}
			]
		},
		{
			"type":2,
			"name":"特惠商品",
			"product":[]
		}
	]
	
	
}
Copy after login

2.php file

 <?php
  echo "获取页面传来的参数";
  $type = $_GET[&#39;type&#39;];
  $proId = $_GET[&#39;id&#39;];
  echo $type."产品type";
  echo $proId."产品Id";
  // 从文件中读取数据到PHP变量 
  $json_string = file_get_contents(&#39;json/data.json&#39;); 
   
  // 用参数true把JSON字符串强制转成PHP数组 
  $data = json_decode($json_string, true); 
   
  // 显示出来看看 
  // var_dump($json_string); 
  // var_dump ($data); 
  // print_r($data); 
  //产品循环
  function foreachFun($d,$type,$proId)
  {
   foreach ($d["goods"] as $key => $value) {
     if($value["type"] == $type){
      $results = $value;
     }
   }
   foreach ($results["product"] as $key => $value) {
     if($value["id"] == $proId){
      $result = $value;
     }
   }
   return $result;
  }
  $res = foreachFun($data,$type,$proId);
  print_r($res);
 ?>
Copy after login
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Alibaba Cloud Win2016 installation Apache and PHP environment tutorial detailed explanation

Operation of PHP associative array and index array Detailed explanation of steps

The above is the detailed content of What are the methods for php to read local json files?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template