【问题标题】:Use JSON in PHP [closed]在 PHP 中使用 JSON [关闭]
【发布时间】:2014-09-19 08:53:19
【问题描述】:

我使用的一些网站向我提供了有关 IP 的信息,但该网站以 JSON 形式返回的信息,而我不知道 JSON。我想用它来检查用户是否来自 IR 做某事但我不知道如何在 php 中使用 JSON,
这是网站返回的 JSON:

{"address":"0.0.0.0.0","country":"IR","stateprov":"somewhere ","city":"Tehr\somewhere (somewhere)"}

我想将国家保存在一个变量中并将此代码添加到我的网站:

<?php
if($country == 'IR'){
//Do somethong  
}

$country是从网站返回的国家名称,

【问题讨论】:

标签: php json


【解决方案1】:

您需要使用json_decode()

$s = '{"address":"0.0.0.0.0","country":"IR","stateprov":"somewhere ","city":"Tehrsomewhere (somewhere)"}';

$d = json_decode($s);

返回:

stdClass Object
(
    [address] => 0.0.0.0.0
    [country] => IR
    [stateprov] => somewhere 
    [city] => Tehrsomewhere (somewhere)
)

这将允许您像这样检查国家/地区/其他字段:

if($d->country == 'IR') {
    // do something
}

注意:您的 "city" 字段中有错误(无效的 json),\ 使其无效。

Example


您可以通过在JSON Lint 处检查来确保您的 json 有效。

【讨论】:

  • 一个问题我如何在我的 php 中使用 [country] if?
  • @King_Far 查看更新的答案。您将使用我发布的示例中的$d-&gt;country。 (将其用作对象,而不是数组
【解决方案2】:

我认为您正在寻找函数json_decode。它解码JSON string

See the documentation here

【讨论】:

    【解决方案3】:

    你必须先解码这个 json 字符串。

    $data = '{"address":"0.0.0.0.0","country":"IR","stateprov":"somewhere ","city":"Tehr\somewhere (somewhere)"}';
    
    $decodeData = json_decode($data);
    

    然后像这样在php中使用这个解码json字符串。

    if($decodeData->country == 'IR'){
    //Do somethong  
    }
    

    【讨论】:

    • 你和@Darrens 的回答有什么不同?除了变量名?
    【解决方案4】:

    首先我想告诉你,给定的 json 是无效的。由于"\""city" : "Tehr\somewhere (somewhere)" 无效。

    所以把它改成下面给定的格式。

    $jsonEncode = { "address": "0.0.0.0.0","country": "IR","stateprov": "somewhere ","city": "There somewhere (somewhere)"}
    
    $jsonDecode = json_decode($jsonEncode,true);
    

    现在您将获得数组格式的值。

    Array(
        [address] => 0.0.0.0.0
        [country] => IR
        [stateprov] => somewhere 
        [city] => There somewhere (somewhere)
    
    );
    

    print_r($jsonDecode['city']); 会给你城市名称或详细信息

    【讨论】:

      猜你喜欢
      • 2015-06-08
      • 2020-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-20
      • 2011-06-10
      • 2013-05-16
      • 2012-03-24
      相关资源
      最近更新 更多