[英]Parsing JSON / associative arrays in from Twitter API response in PHP
[英]parsing a json response from an API with PHP
我正在尝试解析来自API的json响应但是购买改变我创建的一些现有PHP代码但是我遇到了困难。 这是json的回应
"response":{
"status":"ok",
"userTier":"free",
"total":10,
"startIndex":1,
"pageSize":10,
"currentPage":1,
"pages":1,
"results":[{
"id":"lifeandstyle/series/cycling",
"type":"series",
"webTitle":"Cycling",
"webUrl":"http://www.guardian.co.uk/lifeandstyle/series/cycling",
"apiUrl":"http://content.guardianapis.com/lifeandstyle/series/cycling",
"sectionId":"lifeandstyle",
"sectionName":"Life and style"
}
试图解析“webTitle”和“webUrl”部分中的所有信息
<?php
require_once 'Zend/Json.php';
$val = Zend_Json::decode($result);
$arr = $val;
if(preg_match_all("~<p>([\s\S]*?)</p>~i", $arr['parse']['text']['*'], $matches)){
if(is_array($matches[1])) foreach($matches[1] as $paragraph){
echo $paragraph;
}
}
?>
这段代码只解析p标签中的内容,我该如何改变它?
谢谢
我不是100%明确你的问题。 Zend_Json :: decode使用了引擎盖下的json_decode,这就是@psion所指的内容。 我假设你的例子中有$ result
$val = Zend_Json::decode($result);
握住你事先粘贴的json。
它看起来像你发布的json无效或至少不完整(因为有一个缺失]和一个缺失} )。 我不确定这与解析p标签有什么关系,但无论如何这里是一个解析json并提取你感兴趣的组件的例子。它解除了前面的“响应”:来自json的位,然后解码为好。
<?php
$sJson = '"response":{
"status":"ok",
"userTier":"free",
"total":10,
"startIndex":1,
"pageSize":10,
"currentPage":1,
"pages":1,
"results":[{
"id":"lifeandstyle/series/cycling",
"type":"series",
"webTitle":"Cycling",
"webUrl":"http://www.guardian.co.uk/lifeandstyle/series/cycling",
"apiUrl":"http://content.guardianapis.com/lifeandstyle/series/cycling",
"sectionId":"lifeandstyle",
"sectionName":"Life and style"
}]}';
$sJson = substr($sJson, strpos($sJson, ':') + 1);
// feel free to replace json_decode w/ Zend_Json::decode
$aNative = json_decode($sJson);
$sWebTitle = $aNative->results[0]->webTitle;
$sWebUrl = $aNative->results[0]->webUrl;
echo 'Web Title: ' . $sWebTitle . PHP_EOL;
echo 'Web URL : ' . $sWebUrl . PHP_EOL;
这是脚本的输出
Web Title: Cycling
Web URL : http://www.guardian.co.uk/lifeandstyle/series/cycling
解析是什么意思? 您可以在解码后立即使用JSON回复。 你没有$arr['parse']...
你有$arr['webTitle']
其中包含“Cycling”。 你想在“骑自行车”中解析什么?
另外,将结果分配给$ val然后将$ val分配给$ arr的处理是什么? 直接分配给$ arr。
做print_r($ val)并看看你有什么。 这样可以让您更好地了解自己需要做什么。 很可能你的事情比他们需要的更复杂。
PHP中的json函数不需要调用Zend函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.