Iterate through JSON object not working in PHP - php

I'm trying to get data loaded from a url.
The data is given as below
{
"UFs":
[
{
"Valor" : "26.348,83",
"Fecha" : "2017-01-01"
},
{
"Valor" : "26.349,68",
"fecha" : "2017-01-02"
}
]
}
My PHP code so far looks like this:
ini_set("allow_url_fopen", 1);
$url = 'http://api.sbif.cl/api-sbifv3/recursos_api/uf/2017?apikey=472d79589e5bda11f1f032e62047911541c8a937&formato=json';
$obj = json_decode(file_get_contents($url), true);
foreach($obj as $item) {
echo $item['Valor'] . "<br/>";
}
The problem is I'm getting blank screen everytime I tried. I also tried using curl to read the url as below:
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, 'http://api.sbif.cl/api-sbifv3/recursos_api/uf/2017?apikey=472d79589e5bda11f1f032e62047911541c8a937&formato=json');
$result = curl_exec($ch);
curl_close($ch);
$obj = json_decode($result);
foreach($obj as $item) {
echo $item['Valor']."<br/>";
}
But it doesn't work either. I guess the problem is on my for each loop, or the way I'm trying to read the array.

The values are inside UFs object. Use the foreach loop this way:
foreach($obj['UFs'] as $item) {
echo $item['Valor'] . "<br/>";
}

Related

Is there a way to get value of json object from a URL in PHP?

So i am trying to get values of json object from a url, when i hit that url on post man i get something like this
{
"error": "0",
"errorString": "",
"reply": {
"nonce": "5e415334832a8",
"realm": "VMS"
}
}
So, i am trying to write a php code that displays the value of nonce in the browser but it is not working
i have the following code
$getNonceUrl = "https://example.com/api/getNonce";
$getContect = file_get_contents($getNonceUrl);
$jsonNoce = json_decode($getContect, true);
$dd = $jsonNoce->reply[0]->nonce;
echo $dd;
I also did this
$ch = curl_init("https://example.com/api/getNonce");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
$data = curl_exec($ch);
curl_close($ch);
echo $ch->reply[0]->nonce;
But it does not seem to work still.
Below your 2 code samples with suggested corrections.
Using file_get_contents : remove 2nd argument of json_decode
$getNonceUrl = "https://example.com/api/getNonce";
$getContect = file_get_contents($getNonceUrl);
$jsonNoce = json_decode($getContect); // note removal of 2nd parameter
$dd = $jsonNoce->reply[0]->nonce;
echo $dd;
Using curl : you forgot to parse curl output with json_decode
$ch = curl_init("https://example.com/api/getNonce");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
$data = curl_exec($ch);
curl_close($ch);
$data = json_decode($data); // added this line, because curl doesn't decode json automatically
echo $ch->reply[0]->nonce;

PHP parse array data using file_get_contents($url)

I have the following data I pulled from an API using PHP's file_get_contents($url), I would like to parse this data and put each comma separated value into a variable whilst looping to the next set (there are thousands of row, I simply extracted the first two), I have tried parsing methods however most have an element consisting of the datalabel:data, any assistance would be gladly appreciated.
[[1610223840000,"3.63410000","3.65100000","3.62900000","3.64150000","14194.01000000",1610223899999,"51684.84892800",195,"7619.89000000","27756.15839400","0"],[1610223900000,"3.64610000","3.65090000","3.63410000","3.65000000","2219.73000000",1610223959999,"8090.68646600",46,"1176.75000000","4290.44934900","0"]]
Ok figured this out today, for anyone who needs it
$ch = curl_init();
$url = "https://api.blahblahblah";
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
$result = curl_exec($ch);
curl_close($ch);
$obj = json_decode($result, true);
foreach ($obj as $key => $value) {
echo $value[0] . "<br>";
echo $value[1] . "<br>";
}

Remove item from JSON returned from API

I'm new to PHP and have some trouble trying to delete an item from some data returned by an API
function getData()
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_POSTFIELDS, "");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json',));
$data = curl_exec($ch);
echo $data;
exit();
}
Here is the JSON data, I want to remove the item with Id 11, how can I do this?
{
"Data": [
{
"Id": 11,
"Name": "Name1"
},
{
"Id": 12,
"Name": "Name2"
}
]
}
Decode the data.
Remove the item from the array.
Optionally encode it again as string if needed.
$dataArray = json_decode($data, true);
foreach ($dataArray['Data'] as $key => $item) {
if ($item['Id'] === 11) {
unset($dataArray['Data'][$key]);
}
}
$data = json_encode($dataArray);
it will work
$dataArray = json_decode($data, true);
$dataArray['Data'] = array_filter($dataArray['Data'], function($el){return $el["Id"]<>11;});
$data = json_encode($dataArray);
One way is to re-index by Id and unset it:
$array = array_column(json_decode($data, true)['Data'], null, 'Id'));
unset($array[11]);
Now $array is indexed by Id. If you want to reset it, then:
$array = array_values($array);

PHP CURL Error : Data returning NULL Value

I have a JSON code which I put in JSON file named data.json
the JSON Code is :
[
{"value":"23","date":"03/2018"},
{"value":"43","date":"03/2019"},
{"value":"34","date":"12/2017"},
{"value":"13","date":"01/2019"},
{"value":"34","date":"02/2019"}
]
Now The php Code I am using to fetch the data is as Follows :
$url = "data.json" ;
$ch = curl_init() ;
curl_setopt($ch, CURLOPT_URL, $url) ;
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch) ;
$data = json_decode($result, true) ;
foreach($data as $mydata)
{
$data1 = $mydata["value"] ;
$data2 = $mydata["date"] ;
echo $data1 ." : ". $data2 ;
echo "<br/>";
}
I Don't understand what's wrong with the code but it gives an error Warning
Invalid argument supplied for foreach()
This Happens Because the Data is returning NULL Value But I Don't How my JSON Data Format is not correct.
THe Format Looks Fine. But it still returns NULL Value.
You have to provide the full URL of the JSON file if you are using CURL, instead of the data.json
http://localhost/text.json
other options to get the data from json
$result = file_get_contents($url);
The probleme here is :
1- you can't curl the same host , you must use function file_get_content() to get your json like :
<?php
$string = file_get_contents("./data.json");
$data = json_decode($string, true);
foreach($data as $mydata)
{
$data1 = $mydata["value"] ;
$data2 = $mydata["date"] ;
echo $data1 ." : ". $data2 ;
echo "<br/>";
}
if you want to use curl , it must be another host like:
<?php
$url = "http://date.jsontest.com" ;
$ch = curl_init($url) ;
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => array('Content-type: application/json')
);
curl_setopt_array( $ch, $options );
$result = curl_exec($ch);
curl_close($ch) ;
$result = json_decode($result, 1);
foreach($result as $key => $mydata)
{
echo $key ." : ". $mydata ;
echo "<br/>";
}
so it depend of the structural of your Json
thanks
It works fine for me.Please check.
<?php
$url = "http://raveesh.rnd/data.json" ;
$ch = curl_init() ;
curl_setopt($ch, CURLOPT_URL, $url) ;
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch) ;
$data = json_decode($result, true) ;
foreach($data as $mydata)
{
$data1 = $mydata["value"] ;
$data2 = $mydata["date"] ;
echo $data1 ." : ". $data2 ;
echo "<br/>";
}
?>
Output:
23 : 03/2018
43 : 03/2019
34 : 12/2017
13 : 01/2019
34 : 02/2019
when using cUrl with file name only, the cUrl think that it's an url so you will got error
curl: (6) Could not resolve host
if it's a local file, i will prefer to use file_get_contents...
$json = file_get_contents("file.json");
put here your json decode and logic
and in case of url to use the curl.
to answer and help you, let's try to see if you got any errors from curl...
change the code like that and update us
try to use curl_error and check if there are any errors from cUrl,
what you get?
$url = "data.json" ;
$ch = curl_init() ;
curl_setopt($ch, CURLOPT_URL, $url) ;
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
if (curl_error($ch)) {
$error_msg = curl_error($ch);
}
curl_close($ch) ;
if (isset($error_msg)) {
// TODO - Handle cURL error accordingly
}
// put here your json decode and logic

How to Read Xml data using codeigniter?

I want to read xml data using curl in codeigniter. I have create a helper file which will read data from following url: http://www.ekidata.jp/api/l/11302.xml but problem is that i cannot read the data from this url. plz help
Here is my helper file structure:
if (!function_exists('ekidata')) {
function ekidata($type, $code)
{
$apiurl = 'http://www.ekidata.jp/api/'.$type.'/'.$code.'.xml';
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $apiurl);
$response = curl_exec($ch);
curl_close($ch);
$xml = simplexml_load_string($response);
if ($type == 'l') {
return $xml;
} else {
}
}
}
Here is my controller:
function ekidatatest()
{
$this->load->view('ekidatatest');
}
Here is my view:
<?php echo ekidata('l', 11302);?>
I have tested your code and it works ok, the only issue i see is that you are tryin to echo an object (the returned XML variable), try:
print_r (ekidata('l', 11302));
and you should see all the xml object from the file, then you can loop on the object and get the data you need. So if you want the first station name you can get it like this:
$r = ekidata('l', 11302);
echo $r->station[0]->station_name;
and to loop on all stations:
foreach($r->station as $station) {
echo $station->station_name.'<br/>';
}

Categories