使用PHP从url响应json响应

时间:2017-03-14 10:17:52

标签: php json zillow

我在我的网站上使用zillow api

{
request: {
address: "13546 36th Ave NE",
citystatezip: "Seattle, WA"
},
message: {
text: "Request successfully processed",
code: "0"
},
response: {
results: {
result: {
zpid: "48897608",
links: {
homedetails: "http://www.zillow.com/homedetails/13546-36th-Ave-NE-Seattle-WA-98125/48897608_zpid/",
graphsanddata: "http://www.zillow.com/homedetails/13546-36th-Ave-NE-Seattle-WA-98125/48897608_zpid/#charts-and-data",
mapthishome: "http://www.zillow.com/homes/48897608_zpid/",
comparables: "http://www.zillow.com/homes/comps/48897608_zpid/"
},
address: {
street: "13546 36th Ave NE",
zipcode: "98125",
city: "Seattle",
state: "WA",
latitude: "47.727631",
longitude: "-122.289193"
},
zestimate: {
amount: "393735",
last-updated: "03/12/2017",
oneWeekChange: {
@attributes: {
deprecated: "true"
}
},
valueChange: "24606",
valuationRange: {
low: "374048",
high: "413422"
},
percentile: "0"
},
localRealEstate: {
region: {
@attributes: {
name: "Cedar Park",
id: "271831",
type: "neighborhood"
},
zindexValue: "547,700",
links: {
overview: "http://www.zillow.com/local-info/WA-Seattle/Cedar-Park/r_271831/",
forSaleByOwner: "http://www.zillow.com/cedar-park-seattle-wa/fsbo/",
forSale: "http://www.zillow.com/cedar-park-seattle-wa/"
}
}
}
}
}
}
}

以上是我从Zillow Api获得的回复,我从回复中获取了值,如下所示:

zpid => 48897608
links:
homedetails => http://www.zillow.com/homedetails/13546-36th-Ave-NE-Seattle-WA-98125/48897608_zpid/
graphsanddata => http://www.zillow.com/homedetails/13546-36th-Ave-NE-Seattle-WA-98125/48897608_zpid/#charts-and-data
mapthishome => http://www.zillow.com/homes/48897608_zpid/
comparables => http://www.zillow.com/homes/comps/48897608_zpid/
address:
street => 13546 36th Ave NE
zipcode => 98125
city => Seattle
state => WA
latitude => 47.727631
longitude => -122.289193
zestimate:
amount => 393735
last-updated => 03/12/2017

我使用下面的代码获得了这个:

$jsonIterator = new RecursiveIteratorIterator(
    new RecursiveArrayIterator(json_decode($json, TRUE)),
    RecursiveIteratorIterator::SELF_FIRST);

foreach ($jsonIterator as $key => $val) {
    if(is_array($val)) {
        echo "$key:\n";
    } else {
        echo "$key => $val\n";
    }
}

现在我的问题是如何获得单个值,如下面的格式?

<li>zipid:48897608</li>
<li>low:374048</li>

<li>last-updated:03/12/2017</li>

2 个答案:

答案 0 :(得分:0)

这是因为列表标签在页面上被处理为html标签。换句话说,它不是作为纯文本处理的。 在这种情况下,我们应该替换&#39;&lt;&#39;和&#39;&gt;&#39;用&#39;&amp; lt&#39;和&#39;&amp; gt&#39;。

这是代码行。

foreach ($arr as $key=>$val) {
    echo "&ltli&gt{$key}:{$val}&lt/li&gt";
    echo '<br>';
}

希望它对你有所帮助。

谢谢!

答案 1 :(得分:0)

我认为答案就在您的问题中,只需修改您的if条件:

echo '<ul>';
foreach ($jsonIterator as $key => $val) {
    if(!is_array($val)) {
        echo '<li>'.$key.':'.$val.'</li>';
    } 
}
echo '</ul>';