My code is:
$requesturl='https://blockchain.info/tx-index/1fda663d2584425f192eae045d3809950883ebe50f2222f98ef7d31f414f3f96?format=json';
$ch=curl_init($requesturl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$cexecute=curl_exec($ch);
curl_close($ch);
$result = json_decode($cexecute,true);
// to get the first i use
echo $result['out'][0]['addr'];
to get the second I use
echo $result['out'][0]['addr'];
Now my requirement is to look through the array using for each but its throwing error:
foreach ($result['out'] as $adressee) {
echo $adressee.'<br>';
}
for($i=0; $i<count($result['out']); $i++) {
echo $result['out'][$i]["addr"].'<br>';
}
Some Sample codes in PHP manual helped me come up with this solution
Related
is there a way in PHP, perhaps with an external library, to stream results from an API that responds with JSON data?
For instance I have the following code to get the data:
$resultsAPI = "https://www.example.com/api/results.json?
app_id=$app_id&token=$token&page=1&limit=10";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $resultsAPI);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Accept: application/json;api_version=2' ));
$resp = curl_exec($curl);
curl_close($curl);
$results = json_decode($resp, true)['results'];
foreach ($results as $key=>$resultImage) {
$resultImage= "$resultImage[images]?app_id=$app_id&token=$token";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $resultImage);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$resp = curl_exec($curl);
curl_close($curl);
$image = json_decode($resp, true);
$results[$key]['image1'] = $image['image1'];
}
echo '<div class="card"><ul>';
foreach ($results as $result) {
echo '<li>';
echo '<span><p>'.$result['title'].'</p></span>';
echo '<span><p>'.$result['description'].'</p></span>';
echo '<span><img src="'.$result['image1'].'"></span>';
echo '</li>';
}
echo '</ul></div>';
It can take some time to load all data because it is going to loop over some large files. Is it possible to start streaming the results when it has the first data?
In the image below it shows what I am trying to explain. The data is being loaded in to the skeleton one by one:
Any thoughts on this would be very helpful and or if it is possible at all.
I think you're run into the wrong direction.
HTML begin to render after load all the html. So fetch the html with stream is not work for you.
In the demo, it just load a simple html page. Then load the other parts of the page with something like ajax. Each time a part loaded then render it.
Why not merge the the foreach loops? I haven't tested this but items should be echoed very iteration.
echo '<div class="card"><ul>';
foreach ($results as $key=>$result) {
$resultImage= "$result[images]?app_id=$app_id&token=$token";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $resultImage);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$resp = curl_exec($curl);
curl_close($curl);
$image = json_decode($resp, true);
$results[$key]['image1'] = $image['image1'];
echo '<li>';
echo '<span><p>'.$result['title'].'</p></span>';
echo '<span><p>'.$result['description'].'</p></span>';
if(isset($image['image1'])){
echo '<span><img src="'.$result['image1'].'"></span>';
}
echo '</li>';
}
echo '</ul></div>';
I hope that helps
As Kris Roofe said you may need ajax or axios call to output your data with some effects and animations exactly like the image that you attached in your question, your application need to be rendered first with all of it's HTML tags and assets like CSS and Javascript files then you can output some data and show it with animations by using ajax or axios and ofcurse you have more control over your data streaming in this case by using ajax or axios in client-side but you can also do it in your server-side but typically I prefer to do these things in client-side.
by the way if you insist to doing this in this way you can use flush() and ob_flush() to immediately output your data before the while loop ends.
Someone has already mentioned this in php official documentation link. You can check and read full documentation about output buffering and these methods.
You should merge your two foreach loops together and then add these two methods add the end of your loop so it will make it to output your data immediately after each loop iterate.
foreach($results as $key=>$resultImage){
//fetch images data such as title, description, and image itself in this loop
// and aslo echo your html tags in here.
// echo '<li>';
// echo '<span><p>'.$result['title'].'</p></span>';
// echo '<span><p>'.$result['description'].'</p></span>';
// echo '<span><img src="'.$result['image1'].'"></span>';
// echo '</li>';
}
I wrote some comments in your for loop to show you that you should merge your loops together, because you are trying to initialize $results variable in your first loop, and then after finishing that loop you are iterating in $results variable to show output data. so you can't output data immediately with two loops in here because your second loop depends on first one and it will not start iterating until the first one finishes. check this little code that I wrote to demonstrate the usage of these two methods:
$curl = curl_init();
for($i=0;$i<5;$i++){
curl_setopt($curl, CURLOPT_URL, 'example.com');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($curl);
$output = json_decode($output);
foreach($output as $key=>$value){
echo 'key: '.$key;
echo '$value: '.$value;
ob_flush();
flush();
}
}
I would highly recommend you to read about output buffering to implement it correctly in your projects.
I hope this could help you.
HTML starts rendering when some of it arrives. It does not have to be complete source. In PHP you can "send what you already echoed" via ob_flush() and flush() calls. This way it will immediately display in the browser. This can be paired with JSON stream parsing using for example halaxa/json-machine, so the result can look something like this:
<?php
echo '<div class="card"><ul>';
foreach (JsonMachine::fromStream($jsonStreamResource) as $result) {
echo '<li>';
echo '<span><p>'.$result['title'].'</p></span>';
echo '<span><p>'.$result['description'].'</p></span>';
echo '<span><img src="'.$result['image1'].'"></span>';
echo '</li>';
ob_flush();
flush();
}
echo '</ul></div>';
Fetch limited records while rendering html first load. Once page load fully then call a ajax function which will fetch next page rows. Definitely it is the tested method.
<script>
var items = [{item1}, {item2}];
$(document).ready(function() {
$.each(items, function(index, item) {
$('.card').append('<li>'+ '<span><p>'+item['title']+'</p></span>' +
'</li>');
});
});`enter code here`
</script>
OR
You may call ajax function for first page records after html rendered fully.
How do I load a JSON object from a file with ajax?
I'm trying to debug some code using either of these two intrepreters. The code below runs on my GoDaddy site and produces the appropirate output arrays. But, won't run in either of these intrepreters.
Is there a way to modify this code to run in the intrepreters so I can get past line 2 of the code? I inclcuded phpinfo(INFO_MODULES); at the end as an aid.
OR do you know of an online intrepreter that will run this code?
https://3v4l.org/
http://www.runphponline.com/
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = '';
curl_setopt($ch, CURLOPT_URL, "https://api.iextrading.com/1.0/stock/market/batch?symbols=aapl,tsla,ge&types=quote,earnings,stats");
$data = curl_exec($ch);
curl_close($ch);
$data = json_decode($data, true);
// debug -------------------------------
echo ' - ';
echo (count($data)); // number of elements
echo " - " . "<br />\n";
var_dump_pre($data); // dump the array
echo "-" . "<br />\n";
echo "xxxxxxxxxxxxxx-" . "<br />\n";
function var_dump_pre($mixed = null) {
echo '<pre>';
var_dump($mixed);
echo '</pre>';
return null;
}
phpinfo(INFO_MODULES);
?>
http://php.net/manual/en/curl.installation.php
It looks like there are some dependancies that you have to install to use curl_init.
It looks like some poor sap did the work for you at http://phpfiddle.org/
Your code works there.
Since the code ran on my GoDaddy site I was able to copy the data returned from the '$data = curl_exec($ch);' insruction and assign it to a variable name at the start of the code I'm trying to debug. So, the code I'm trying to debug starts out with the intended incomimg data (and doesn't have to go get it). I can now continue to use any of these three online intrepreters:
https://3v4l.org/
http://www.runphponline.com/
http://phpfiddle.org/
I am trying to retrieve an array from an API, but every time it is returning an empty array after every attempt.
This is my coding which is fetching data from api:
<?php
$array=array("name"=>"name1");
$url = "http://getsjobs.esy.es/registerapi.php?".http_build_query($array);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$json = curl_exec($ch);
curl_close($ch);
$data = json_decode($json,true);
if (is_array(json_decode($data )) || is_object(json_decode($data)))
{ echo 'array exists'; }
else { echo 'Not an array'; }
?>
this is my api code
<?php
if(isset($_GET['Array'])) {
$array = $_GET['Array'];
header('Content-type: application/json');
}
?>
Even if i use json_encode($array). It is returning empty array. I can receive single value or single array element, but not able to send and receive entire
array from json.
I am not able to find any relevant post. Any link or suggestion will be helpful
My PHP is rusty, but the problem looks to me to be because your API is looking for a parameter called "Array", but nowhere in your calling block does it actually send a GET parameter called "Array".
Your code looks a bit incomplete, so maybe I'm misunderstanding something.
look here: you're decoding it twice.
$data = json_decode($json,true);
if (is_array(json_decode($data )) || is_object(json_decode($data)))
{ echo 'array exists'; }
else { echo 'Not an array'; }
simply:
$data = json_decode($json,true);
if (is_array($data ))
{ echo 'array exists'; }
else { echo 'Not an array'; }
if it still doesn't works, see what echo json_last_error_msg(); returns.
Try to check if your $json is a valid json too. Check if what echo $json; returns is valid here: http://jsonformatter.curiousconcept.com/
I know this has been done to death.
but i am really strugling
I have put together a webservice that generates a json,
i can and understand this bit in
// create a new cURL resource
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://marcom.domain.com/corp/pub.php");
curl_setopt($ch, CURLOPT_HEADER, 0);
this will dump out on the page [{"Torders":"3222","name":"john"},{"Torders":"579","name":"Kevin"}]
their is 5 in total but for this i am keeping it simple
I don't understand how to get these as an array so that my end result is a list
of name and Torders
the rendered html would be something like this
<li>john 3222</li>
<li>Kevin 579 </li>
please don't send me to php manual page for json decode cause i am strugling to understand this.
thank you
<?php
$json = file_get_contents('http://marcom.domain.com/corp/pub.php');
$people = json_decode($json);
?>
<ul>
<?php foreach ($people as $person): ?>
<li><?=$person->name?> <?=$person->Torders?></li>
<?php endforeach; ?>
</ul>
If you want to use curl, you'll want to set curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); and get the return from curl_exec()
U need to use json_decode()
$j = '[{"Torders":"3222","name":"john"},{"Torders":"579","name":"Kevin"}]';
$data = json_decode($j,true);
//print_r($data);
echo '<ul>';
foreach($data as $key=>$val){
echo '<li>'.$val['name'].' '.$val['Torders'].'</li>';
}
echo '</ul>';
I'm working with the yahoo api - and pretty much going off their example. BUT I'm getting errors such as: Invalid argument supplied for foreach()
Here is the actual foreach statement:
foreach ($data->query->results->result as $r){
// do something with the data
}
The entire code i'm running is here:
$c =curl_init("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20local.search%20where%20state%3D'delaware'%20and%20city%20%3D%20'smyrna'%20and%20query%3D'pizza'&format=json");
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
curl_setopt($c, CURLOPT_CONNECTTIMEOUT, 20); // query times out after 20 seconds
$data = curl_exec($c); // I asked for data format to be in json in the query it appears to be returned decoded
//print_r($data);
$data = curl_exec($c);
if ($data === FALSE) {
die("Curl failed with error: " . curl_error($c));
}
$data = json_decode($data);
if (is_null($data)) {
die("json_decode failed with error: " . json_last_error());
}
foreach ($data->query->results->result as $r){
// do something with the data
}
$data is a decoded json response - it's got the data and it appears that my structure is right - i just want to loop through and display business names for example - but no go.
It should be $data->query->results->Result. Notice, the Uppercase Result.
To help you with JSON. Paste the whole JSON string into this utility, and see the tree structure visually.
json_decode requires you pass an extra boolean parameter if you want it to return an ARRAY rather than an object.
$data = json_decode($data,TRUE);
if (is_null($data)) {
die("json_decode failed with error: " . json_last_error());
}
foreach ($data['query']['results]'['Result'] as $r){
// do something with the data
}