简体   繁体   English

PHP中的JSON验证和解析

[英]JSON Validation and parsing in PHP

I am parsing JSON using the following example php syntax 我正在使用以下示例php语法解析JSON

$carModel = strip_tags($_REQUEST['car']['model']);

The only problem is that some times the "model" array is missing from the provided JSON. 唯一的问题是,有时所提供的JSON中缺少“模型”数组。 When this is the case my php script shuts down when it reaches that line. 在这种情况下,我的PHP脚本在到达该行时会关闭。 Can any one recommend a way to check for the model array before parsing so that my php scrip will still run if "model" isn't present. 任何人都可以推荐一种在解析之前检查模型数组的方法,以便在不存在“模型”的情况下我的PHP脚本仍然可以运行。

I'm not sure how this is related to json, but if you want to check if a variable exists before you use it, you can do: 我不确定这与json有什么关系,但是如果您想在使用变量之前检查它是否存在,可以执行以下操作:

if (isset($_REQUEST['car']['model']))
{
  $carModel = strip_tags($_REQUEST['car']['model']);
}

Just check to see if it's there. 只要检查它是否在那里。 If not assign a default value to it: 如果未为其分配默认值:

$carModel = (isset($_REQUEST['car']['model'])) ? strip_tags($_REQUEST['car']['model']) : '';

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

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