Echo specific JSON nodes in PHP - php

I made a RSS to JSON file
https://www.dannny0117.com/.well-known/api/news2.php
It works, in that it returns the output as JSON from the RSS source. Now, I want to print only a few elements from that with PHP echo.
According to the JSON, I need to grab channel, item, title and guid since those are the things I want to output.
I only need the 1st post title and link, but my code just won't pick it up because I don't fully know how to access the thing.
Here is the code that I'm using that I think should echo but doesn't:
<?php
$url = "https://www.dannny0117.com/.well-known/api/news2.php";
$content = file_get_contents($url);
$json = json_decode($content, true);
$title = $content['channel']['item'][0]['title'];
$link= $content['channel']['item'][0]['guid'];
echo $title , $link;
?>
This is not a problem with encoding or unicode character, the main problem is that my code CAN'T read the items from the JSON needed.

There are 2 mistakes which you made:
1) You have UTF-8 characters in your json string.
2) You have output of json_decode() string in variable $json but you are using $content.
Use the code below.
$url = "https://www.dannny0117.com/.well-known/api/news2.php";
$content = file_get_contents($url);
$enc = mb_detect_encoding($content);
if($enc == 'UTF-8') {
$content = preg_replace('/[^(\x20-\x7F)]*/','', $content);
}
$json = json_decode($content,true);
$title = $json['channel']['item'][0]['title'];
$link = $json['channel']['item'][0]['guid'];
echo "<pre>";
print_r([$title , $link]);

you can check this link here , it about predefined constants, usually when you deal with none latin letters you can have this kind of mess. try use JSON_UNESCAPED_UNICODE
and this will solve your problem.
you can use something like this:
$json_output = json_decode($content, true, JSON_UNESCAPED_UNICODE);
as you said it did not work so would you try to add this :
$options = array('http' => array(
'header' => 'Accept-Charset: UTF-8'
)
); $context = stream_context_create($options);
$url = "https://www.dannny0117.com/.well-known/api/news2.php";
$content= file_get_contents($url, false, $context);
$json = json_decode($content, true,JSON_UNESCAPED_UNICODE);

Related

formatting json data from a string in php

I am trying to format the data passed by the api in to key value paris for use with javascript the data right now is one big key and not in key value paris how can i get the data as key value paris and properly formated ?
<?php
header('Content-Type: application/json; charset=utf-8');
$url = file_get_contents('https://www.jiosaavn.com/api.php?_format=json&query=mere%20angne%20mein&__call=autocomplete.get');
$data = explode('[', $url);
$format = json_encode($data[1], true);
print_r($format);
?>
The response contains some HTML which has to be removed to be able to parse the json. This can be achieved with strip_tags. After removing the html json_decode can be used to get the values:
<?php
$content = file_get_contents('https://www.jiosaavn.com/api.php?_format=json&query=mere%20angne%20mein&__call=autocomplete.get');
$content = strip_tags($content);
$response = json_decode($content);
print_r($response);
foreach($response->albums->data as $album){
echo $album->title;
}
result:
Mere Angne MeinLaawarisMere Angne MeinMere Angne Mein (From "Mere Angne Mein")Mere Angane Mein
$url = 'https://www.jiosaavn.com/api.php_format=json&query=mere%20angne%20mein&__call=autocomplete.get';
$data = file_get_contents($url);
$format = json_decode($data);
print_r($format);

Issue displaying json feed items using PHP

I am very new to json in combination with php and wonder why the following code is not working. My mission is displaying the title items one by one.
<?php
$json_string = file_get_contents("https://www.fiverr.com/gigs/gigs_as_json?host=search&type=single_query&query_string=pet&search_filter=rating&category_id=3&sub_category_id=49&limit=48");
$parsed_json = json_decode($json_string, true);
$parsed_json = $parsed_json['gigs'];
foreach($parsed_json as $key => $value)
{
echo $value['title'] . '<br>';
}
?>
The next issue will by, how would I be able to save the image item called cloud_img_med to my server into /grabbed
Your help would be greatly appreciated.
To answer your question about why this code isn't working:
I tried to set it up myself, and found out that the output fetched by file_get_contents is compressed. You can see that by reading the output in a simple var_dump:
var_dump($json_string);
To fix this, you'll need to use a custom context with no compression:
$context = stream_context_create(
array(
'http' => array(
'method' => "GET",
'header' => "Accept-Encoding: gzip;q=0, compress;q=0\r\n",
)
));
Then pass it as the third parameter:
$json_string = file_get_contents("https://www.fiverr.com/gigs/gigs_as_json?host=search&type=single_query&query_string=pet&search_filter=rating&category_id=3&sub_category_id=49&limit=48", false, $context);
I should do this JSON string readable
The code seems to work fine - I tried it on my local machine.
Running this
<?php
$str = <<<EOT
// JSON here...
EOT;
$parsed_json = json_decode($str, true);
$parsed_json = $parsed_json['gigs'];
foreach($parsed_json as $key => $value)
{
echo $value['title'] . '<br>';
}
?>
Gives me this output
replace the MGM lion with your pet or whoever<br>design creative Animal And Pet Company logo<br>`
Which is sort of what you want? If you're having trouble, maybe file_get_contents isn't allowed on your server and you can't get the JSON. Try hardcoding it into the $str variable like I did, and see if you get what you want.
With regards to saving the image, you can check this answer here: https://stackoverflow.com/a/724449/4396258
I think the problem might be the data you're getting from Fiverr's JSON API. At least in my test, I found it was using gzip encoding to compress the data you're requesting. So you have to uncompress it.
$json_string = file_get_contents("https://www.fiverr.com/gigs/gigs_as_json?host=search&type=single_query&query_string=pet&search_filter=rating&category_id=3&sub_category_id=49&limit=48");
$content = json_decode(gzinflate( substr($json_string,10,-8) ));
$gigs = $content->gigs;
foreach($gigs as $key => $value)
{
echo $value->title . '<br>';
}

How to output json data in array using curl

I have code here that will get json data using curl. Now I want to echo all data. This will show no output.
<?php
$json = file_get_contents('myurl');
$data = json_decode($json);
print_r($data);
?>
This is json coming from my url:
({"Response_Code":"0000","ResultMobilePrefix":["0917","0905","0906","0915","0916","0926","0927","0937","0935","0817","0936","0922","0923",
"0932","0933","0934","0942","0943","0907","0908","0909","0910","0912","0918","0919","0920","
0921","0928","0929","0930","0938","0939","0948","0949","0925","0989","0999","0947","0998","
0946","0975","0977"]});
All you need is
echo json_encode($json);
Use true to convert it into array;
$data = json_decode($json,true);
echo '<pre>';
print_r($data);
for displaying json in format use json_encode() and for proper format use JSON_PRETTY_PRINT
header('Content-type: application/json');
echo json_encode($json,JSON_PRETTY_PRINT);
you need to get rid of the bracket and semicolon on the JSON file first before you can use the json_decode();
<?php
$json = file_get_contents('myurl');
//remove the brackets
$json = str_replace("(", "", $json);
$json = str_replace(")", "", $json);
//remove the semicolon
$json = str_replace(";", "", $json);
$data = json_decode($json);
print_r($data);
?>
this is a bit ugly, but hope you get the idea, you need to remove that character first
I just want to add to what Manish has explained above. This is what PHP Docs say about the second parameter:
When TRUE, returned objects will be converted into associative arrays.
else you will simply get a stdclass object
The problem is the URL does not return a valid Json
you could simply try
var_dump($data);
this will return null because it's not a valid json see json_decode
this will work
$json = file_get_contents('myurl');
$json = preg_replace('/[ ]{2,}|[\t\n\r\(\)\;]/', '', trim($json));
$data = json_decode($json);
print_r($data);

Decode G2A search results (json) to array

Help me to grab name of games from url
This page output json format.
I try to convert it to array, but my code not work. Please help me!
$url = 'https://search.g2a.com/items/select?json.wrf=jQuery111003403934023808688_1411464896728&q=NOT+type%3Aindividual+AND+(-type%3Agaming+AND+wholesaleQty%3A%5B1+TO+*%5D+AND+wholesaleMinPrice%3A%5B0+TO+198%5D)&wt=json&start=0&rows=10000&sort=sortOrder+DESC&_=1411464896757';
$content = file_get_contents($url);
$json = json_decode($content, true);
echo "<pre>";
print_r($json);
echo "</pre>";
You should remove the JSONP parameter json.wrf from the URL first:
https://search.g2a.com/items/select?q=NOT+type%3Aindividual+AND+(-type%3Agaming+AND+wholesaleQty%3A%5B1+TO+*%5D+AND+wholesaleMinPrice%3A%5B0+TO+198%5D)&wt=json&start=0&rows=10000&sort=sortOrder+DESC&_=1411464896757
This will return a proper JSON result.
The output from that URL (that I get currently starts with):
jQuery111003403934023808688_1411464896728({"responseHeader" ...
This isn't a pure JSON response, but rather a JSONP response.
If you're just trying to parse it in PHP, maybe something like:
$url = ...; // Your URL Here
$data = file_get_contents($url);
$pos = strpos($data, '{');
$data = substr($data, $pos, strlen($data) - $pos - 2);
$json = json_decode($data, true);
echo "<pre>";
print_r($json);
echo "</pre>";

PHP - Getting a URL within a function argument

I have the below function that works perfect when I put the URL string within the argument manually. I need it to be dynamic though and I am using Wordpress.
function get_tweets($url) {
$json_string = file_get_contents('http://urls.api.twitter.com/1/urls/count.json?url=' . $url);
$json = json_decode($json_string, true);
return intval( $json['count'] );
}
// Below is the one that works manually
<?php echo get_tweets('http://www.someurl.com');
//ones I have tried that do not (trying to make dynamic)
$url = $get_permalink();
echo get_tweets('$url');
echo get_tweets($url);
$url = '$get_permalink()';
$url = $get_permalink(); // produces needs to be in string error
echo get_tweets($url);
There is nothing wrong with what you're doing, per se. The only obvious mistake I can see is that you aren't encoding the URL properly. You need to ensure the query string arguments you put in the URL are properly URL encoded, otherwise the remote host may not interpret the request correctly.
function get_tweets($url) {
$json_string = file_get_contents('http://urls.api.twitter.com/1/urls/count.json?url=' . urlencode($url));
$json = json_decode($json_string, true);
return intval( $json['count'] );
}
echo get_tweets('http://www.someurl.com'); // should work just fine
Did you try to urlencode your url String?
urlencode($foo);
Your main problem is on below line
Change
//ones I have tried that do not (trying to make dynamic)
$url = $get_permalink();
To
//ones I have tried that do not (trying to make dynamic)
$url = get_permalink();

Categories