PHP JSON Encode or Decode? [duplicate] - php

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 6 years ago.
So I have some relatively simple JSON I'm trying to display using PHP and I'm getting stuck, I think perhaps I'm not using decode or encode correctly. Maybe I simply overlooked something.
Here's the JSON...
{
"numFound": 43640,
"start": 0,
"maxScore": 0.7847167,
"docs": [],
"facets": {}
}
Here's my PHP...
<?php
$json_returned = file_get_contents("URL_OF_JSON_SOURCE");
$decoded_results = json_decode($array, true);
{
foreach($decoded_results as $results){
echo "Number Found:".$results['numFound'].";
echo "Start:".$results['start'].";
}
}
?>
I'm primarily just trying to get "numFound", "start", and "maxScore" to display. Thanks for any help, or even taking the time to read this post.
Here's the source JSON..
https://api.data.gov/gsa/fbopen/v0/opps?q=technology&data_source=FBO&limit=1&show_closed=true&api_key=CTrs3pcYimTdR4WKn50aI1GcUxyL9M4s1fyBbSer

You don't have any JSON Array in the given data. So firstly you don't have to loop returned data. Secondly you just forget double quotes in the loop. Third you don't have to join strings if you got any of them is null.
Here is the solution :
<?php
$result = json_decode( file_get_contents("sth"), true );
echo 'Number Found :'.$result["numFound"].'<br/>';
echo 'Start :'.$result["start"].'<br/>';

You php code is messed up
<?php
$json_returned = file_get_contents("https://api.data.gov/gsa/fbopen/v0/opps?q=technology&data_source=FBO&limit=1&show_closed=true&api_key=CTrs3pcYimTdR4WKn50aI1GcUxyL9M4s1fyBbSer");
$decoded_results = json_decode($json_returned, true);
echo "Number Found:".$decoded_results['numFound']." ";
echo "Start:".$decoded_results['start'];
?>

Related

How get in PHP value from array JSON response of influxdb

I apologize in advance if there was already a similar question. I tried to find a solution but unfortunately I still can't.
I have a JSON response from influxdb
$output2 = '{"results": [{"statement_id": 0,"series": [{"name": "dbinfluxdb","columns": ["time","count"],"values": [["2020-07-02T00:00:00Z",1],["2020-07-03T00:00:00Z",0],["2020-07-04T00:00:00Z",0],["2020-07-05T00:00:00Z",0],["2020-07-06T00:00:00Z",1],["2020-07-07T00:00:00Z",0]]}]}]}';
and I need to print out the name of columns time and count and values to be able generate a new JSON for Google chart.
What am I able to do now is only get a statement_id=0.
$decode = json_decode($output2,true);
foreach($decode['results'] as $val){
//Actual statement_id is 0
echo "statement_id is ";
echo $val['statement_id'];
echo "<br/>";
}
But I need to print:
time, count<br/>
2020-07-02T00:00:00Z,1<br/>
2020-07-03T00:00:00Z,0<br/>
2020-07-04T00:00:00Z,0<br/>
2020-07-05T00:00:00Z,0<br/>
2020-07-06T00:00:00Z,1<br/>
or put it into the variable to be able to work with it. I already tried without converting into array just with
$decode = json_decode($output2); //without ",true"
Can you please help me how to solve it.
I've spent almost the whole day looking for a solution and I can't find a way to solve the problem.
If you need to print it out on html, just change the \n to <br>
<?php
$output2 = '{"results": [{"statement_id": 0,"series": [{"name": "dbinfluxdb","columns": ["time","count"],"values": [["2020-07-02T00:00:00Z",1],["2020-07-03T00:00:00Z",0],["2020-07-04T00:00:00Z",0],["2020-07-05T00:00:00Z",0],["2020-07-06T00:00:00Z",1],["2020-07-07T00:00:00Z",0]]}]}]}';
$decode = json_decode($output2,true);
echo $decode["results"][0]["series"][0]["columns"][0].",".$decode["results"][0]["series"][0]["columns"][1]."\n";
foreach($decode["results"][0]["series"][0]["values"] AS $el)
{
echo $el[0].",".$el[1];
echo "\n";
}
?>
If i understand you write this would be the code to output the JSON for the Google Chart:
<?php
$output2 = '{"results": [{"statement_id": 0,"series": [{"name": "dbinfluxdb","columns": ["time","count"],"values": [["2020-07-02T00:00:00Z",1],["2020-07-03T00:00:00Z",0],["2020-07-04T00:00:00Z",0],["2020-07-05T00:00:00Z",0],["2020-07-06T00:00:00Z",1],["2020-07-07T00:00:00Z",0]]}]}]}';
$decode = json_decode($output2,true);
$googlechart = array();
$googlechart[] = array($decode["results"][0]["series"][0]["columns"][0],$decode["results"][0]["series"][0]["columns"][1]);
foreach($decode["results"][0]["series"][0]["values"] AS $el)
{
$googlechart[] = array($el[0],$el[1]);
}
echo json_encode($googlechart);
?>

php json request: json_decode unicode string [duplicate]

This question already has answers here:
PHP json_decode() returns NULL with seemingly valid JSON?
(29 answers)
Closed 1 year ago.
I try to get the contents of this json URL:
http://www.der-postillion.de/ticker/newsticker2.php
Problem seems to be that the contents of "text" have Unicode within.
Everytime I try to get the json_decode, it fails with NULL...never had that issue before. always pulling json that way:
$news_url_postillion = 'http://www.der-postillion.de/ticker/newsticker2.php';
$file = file_get_contents($news_url_postillion, false, $context);
$data = json_decode($file, TRUE);
//debug
print_r(array($data));
$news_text = $data['tickers'];
//test
echo $news_text->text[0]; //echo first text element for test
foreach($news_text as $news){
$news_text_output = $news->{'text'};
echo 'Text:' . echo $news_text_output; . '<br>';
}
Anybody any idea what is wrong here? tries to get encoding working for hours with things like:
header("Content-Type: text/json; charset=utf-8");
or
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Content: type=application/json\r\n" .
"Content-Type: text/html; charset=utf-8"
)
);
$context = stream_context_create($opts);
but no luck :(
Thanks for your help!
Solution:
the json source has some unwanted elements in it, like the BOM character at json start. I could not influence the source json, so the solution walkingRed provided put me on the right track. Only the utf8_decode was needed due to his code is only for english language without special characters.
My working code solution for parsing and output the json is:
<?php
// Postillion Newsticker Parser
$news_url_postillion = 'http://www.der-postillion.de/ticker/newsticker2.php';
$json_newsDataPostillion = file_get_contents($news_url_postillion);
// Fix the strange json source BOM stuff
$obj_newsDataPostillion = json_decode(preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $json_newsDataPostillion), true);
//DEBUG
//print_r($result);
foreach($obj_newsDataPostillion['tickers'] as $newsDataPostillion){
$newsDataPostillion_text = utf8_decode($newsDataPostillion['text']);
echo 'Text:' . $newsDataPostillion_text . '<br>';
};
?>
I made some search and get this:
$result = json_decode(preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $file), true);
Original post
BOM! There is a BOM character at the beginning of the document which you linked and you need to remove it before you try to decode its content.
You can see it e.g. if you would download that json with wget and display it with less.

PHP Display JSON [duplicate]

This question already has answers here:
Handling data in a PHP JSON Object
(3 answers)
Closed 8 years ago.
I want to do the following in PHP:
Get json data from http://domain.com/api/user/1
This provides:
{"name":"Joe","password":"something","email":"something#something.com"}
I want to be able to do a simple php echo to display the json data on a webpage
<html><?php echo $password ?></html>
<html><?php echo $name ?></html>
<html><?php echo $email ?></html>
So basically, creating a php for the "name" / "password" or "email" part of json results
You can do like this:
<?php
$json = '{"name":"Joe","password":"something","email":"something#something.com"}';
$obj = json_decode($json);
print $obj->{'name'}; // Joe
print $obj->{'password'}; // something
print $obj->{'email'}; // something#something.com
?>
for more info: http://in1.php.net/json_decode

preg_match_all matches unexpectedly [duplicate]

This question already has answers here:
How do you parse and process HTML/XML in PHP?
(31 answers)
Closed 9 years ago.
I've just started PHP and I want to scrape a little page which I can't, I tried doing 'PREG_MATCH_ALL' but it just doesn't get the result I want.. Basically I want to scrape the youtube video links from here only: https://gdata.youtube.com/feeds/api/standardfeeds/most_shared - Scrape all of them and then use them later.
I tried using the following code which failed;
<?php
$data = file_get_contents('https://gdata.youtube.com/feeds/api/standardfeeds/most_shared');
preg_match_all("/src='(.+?)'>/", $data, $links);
$link_out = $links[0][0];
echo $link_out;
?>
I'm new to PHP, so little help please.
Thanks
As the feed is XML, you can use PHP's SimpleXMLElement to obtain the data.
<?php
$xml = new SimpleXMLElement(
'https://gdata.youtube.com/feeds/api/standardfeeds/most_shared',
null,
true
);
foreach($xml->entry as $entry) {
echo $entry->content['src'], PHP_EOL;
}
/*
https://www.youtube.com/v/IjWc43FCYlg?version=3&f=standard&app=youtube_gdata
https://www.youtube.com/v/Xw1C5T-fH2Y?version=3&f=standard&app=youtube_gdata
https://www.youtube.com/v/Kq0_dGKx4Os?version=3&f=standard&app=youtube_gdata
https://www.youtube.com/v/gbcBYs0ljI0?version=3&f=standard&app=youtube_gdata
https://www.youtube.com/v/78juOpTM3tE?version=3&f=standard&app=youtube_gdata
https://www.youtube.com/v/OOiZ-5DqwYI?version=3&f=standard&app=youtube_gdata
https://www.youtube.com/v/zjz614QVyfQ?version=3&f=standard&app=youtube_gdata
https://www.youtube.com/v/h15m87WsCHQ?version=3&f=standard&app=youtube_gdata
https://www.youtube.com/v/SXKOTdyOUBg?version=3&f=standard&app=youtube_gdata
https://www.youtube.com/v/BRAM8MpqIeA?version=3&f=standard&app=youtube_gdata
https://www.youtube.com/v/5yB3n9fu-rM?version=3&f=standard&app=youtube_gdata
https://www.youtube.com/v/NAOo9SnzRH8?version=3&f=standard&app=youtube_gdata
https://www.youtube.com/v/0KtILkzC-1g?version=3&f=standard&app=youtube_gdata
https://www.youtube.com/v/kWSIFh8ICaA?version=3&f=standard&app=youtube_gdata
https://www.youtube.com/v/Mi6AhogZCeg?version=3&f=standard&app=youtube_gdata
https://www.youtube.com/v/kWuIGAZ1x2I?version=3&f=standard&app=youtube_gdata
https://www.youtube.com/v/lKY5fmDGVLs?version=3&f=standard&app=youtube_gdata
https://www.youtube.com/v/C94PaCtqOk4?version=3&f=standard&app=youtube_gdata
https://www.youtube.com/v/V-fL8zopddI?version=3&f=standard&app=youtube_gdata
https://www.youtube.com/v/UWlzMIl7E48?version=3&f=standard&app=youtube_gdata
https://www.youtube.com/v/mcw6j-QWGMo?version=3&f=standard&app=youtube_gdata
https://www.youtube.com/v/-RSDaRttpzk?version=3&f=standard&app=youtube_gdata
https://www.youtube.com/v/8_RDx4skTp4?version=3&f=standard&app=youtube_gdata
https://www.youtube.com/v/7YDWdv9kR0M?version=3&f=standard&app=youtube_gdata
https://www.youtube.com/v/m96tYpEk1Ao?version=3&f=standard&app=youtube_gdata
*/
Anthony.
Try with this pregmatch:
preg_match_all("/src='([^']+)'/si", $data, $links);
and show results:
echo "<pre>";
print_r($links);
<?php
$data = file_get_contents('https://gdata.youtube.com/feeds/api/standardfeeds/most_shared');
preg_match_all("/src='(.+?)'\/>/", $data, $links);
print_r($links[1]);
You forgot to match the closing / of the anchor tags.

PHP json decode with number tag [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to access object properties with names like integers?
I tried to decode the json result from youtube data api by the following code:
$url="http://gdata.youtube.com/feeds/api/videos/$id?v=2&alt=jsonc";
echo "$url".'<BR>';
$json = file_get_contents($url,0,null,null);
$json_output = json_decode($json);
$items=$json_output -> data;
$content = "{$items->content->1}";
echo $content.'<BR>';
Everything works fine but the last two lines. Could someone please help?
And Here is the json result:
{"apiVersion":"2.1","data":{"id":"9jDg3Dh28rE","uploaded":"2012-10-04T03:45:49.000Z",
........
"content":{"5":"http://www.youtube.com/v/9jDg3Dh28rE?version=3&f=videos&app=youtube_gdata",
"1":"rtsp://v5.cache8.c.youtube.com/CiILENy73wIaGQmx8nY43OAw9hMYDSANFEgGUgZ2aWRlb3MM/0/0/0/video.3gp",
"6":"rtsp://v5.cache4.c.youtube.com/CiILENy73wIaGQmx8nY43OAw9hMYESARFEgGUgZ2aWRlb3MM/0/0/0/video.3gp"},"duration":2403,......}}
You need to wrap the numeric property with {} to access it.
$content = $items->content->{1};
And you also don't need to use double quotes like below:
$thumbnail = "{$items->thumbnail->sqDefault}";
This should just be
$thumbnail = $items->thumbnail->sqDefault;

Categories