I have the following code that tests a url address, it returns an object JSON
but I can't access its data. I want to access the data listaMesa
specifically, and show only the data that has content:
<?php
set_time_limit(0);
$ch = curl_init();
//$i es el numero de carnet, lo pueden probar con postman si no confían.
for($i=0; $i<13;$i++)
{
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//La siguiente linea es la pagina del trep, lo pueden cambiar por computo si desean
curl_setopt($ch, CURLOPT_URL, "https://computo.oep.org.bo/resul/mesaElector/$i");
curl_setopt($ch, CURLOPT_HEADER, 0);
$resp=curl_exec($ch);
$json=json_decode("[$resp]");
// aqui deberia de ir un if, pero me da error al utilizar $json->listaMesa o $json["listaMesa"]
var_dump($i,$json);
echo '<br>';
}
curl_close($ch);
?>
How to Access the data of a JSON parcemented to show only the data that has content?
The errors you have are:
curl
that you need it to return the data ( and not print it ) using the optionCURLOPT_RETURNTRANSFER
.$resp
to the functionjson_decode
.Then you need:
if
to validate that the array$json->listaMesa
is not empty.$json->listaMesa
you can useforeach
.Solution: