DrunkenMonkey
DrunkenMonkey

Reputation: 36

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);

    ?>

Upvotes: 0

Views: 105

Answers (2)

MaartenDev
MaartenDev

Reputation: 5802

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

Upvotes: 1

Frederick Behrends
Frederick Behrends

Reputation: 3095

$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);

Upvotes: 0

Related Questions