Getting JSON data from Rest API [closed] - php

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I am using a Rest API to get data from a website and I would like to use that data in my webshop. I have never worked with API's before.
I now have the following code:
<?php
$url = 'https://api.floraathome.nl/v1/products/get?apitoken=[MY_API_TOKEN]&type=json';
$json = file_get_contents($url);
$retVal = json_decode($json, TRUE);
for ($x = 0; $x < count($retVal); $x++) {
echo $retVal['data'][$x]['dutchname']."<br>";
echo $retVal['data'][$x]['purchaseprice']."<br>";
echo $retVal['data'][$x]['promotionaltext']."<br><br>";
}
My problem is that it only shows the first 2 products, but I have 9 products selected. If I print $retVal, it does output all 9 products.

That's why i always prefer foreach(), do like below:-
foreach($retVal['data'] as $retV){
echo $retV['dutchname']."<br>";
echo $retV['purchaseprice']."<br>";
echo $retV['promotionaltext']."<br><br>";
}
Note:- your code will also work if you change count($retVal) to count($retVal['data'])

My problem is that it only shows the first 2 products, but I have 9
products selected. If I print $retVal, it does output all 9 products.
Thats because you are looping over the wrong count of your elements:
for ($x = 0; $x < count($retVal); $x++)
^^^^^^^^^^^^^^
as you can see, the problem is in here count($retVal) which I assume that the structure is like something like that:
Array (
[data] => Array ()
[xxxx] => 'xx'
)
so to solve this, -and if you want to go with for loop rather than the other right solution using foreach- you will need to get the prober count count($retVal['data']):
for ($x = 0; $x < count($retVal['data']); $x++) {
echo $retVal[$x]['dutchname']."<br>";
echo $retVal[$x]['purchaseprice']."<br>";
echo $retVal[$x]['promotionaltext']."<br><br>";
}

Related

php break not working as intended? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I have a for loop that loops through xml. I then fetch results from the database and look for the id.
What happens is that when an id is found and the break happens, it stops both the while loop and the parent for loop. I just want to stop the while loop. How do I get this to work as intended?
$xml = simplexml_load_file('file/path/here');
$articles = $xml->article;
$total_articles = count($articles);
// Cycle through the list of articles
for($a=0; $a<$total_articles; $a++)
{
// Check if article already exists
// MySQLi select statement goes here
$exists = false;
while($a = $article_result->fetch_assoc())
{
if($a['article_id'] == $id)
{
$exists = true;
break 1;
}
}
}
you're setting $a to $article_result->fetch_assoc().
Here:
...
while($a = $article_result->fetch_assoc())
...
[] < 1 returns false for me, at least for php7.

unable to a decode_json in php [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have A Json data But I am unable to get desired response.
$content='{"success":true,"results":[{"id":"21390fb46e92","msisdncountrycode":"DE","msisdn":"+491788735000","statuscode":"HLRSTATUS_UNDELIVERED","hlrerrorcodeid":9,"subscriberstatus":"SUBSCRIBERSTATUS_ABSENT","imsi":null,"mccmnc":"26203","mcc":"262","mnc":"03","msin":null,"servingmsc":null,"servinghlr":null,"originalnetworkname":"E-Plus","originalcountryname":"Germany","originalcountrycode":"DE","originalcountryprefix":"+49","originalnetworkprefix":"178","roamingnetworkname":null,"roamingcountryname":null,"roamingcountrycode":null,"roamingcountryprefix":null,"roamingnetworkprefix":null,"portednetworkname":null,"portedcountryname":null,"portedcountrycode":null,"portedcountryprefix":null,"portednetworkprefix":null,"isvalid":"Yes","isroaming":"No","isported":"No","usercharge":"0.0100","inserttime":"2015-11-24 18:56:42.048693+08","storage":"CURL-TEST","route":"IP1"}]}';
i want to capture some contents like
id , msisdncountrycode , msisdncountrycode , statuscode , hlrerrorcodeid
And Other Values As Well Please Help To Solve This problem .
check out this:
$result = json_decode($content);
var_dump($result->results[0]->id);//will get id
var_dump($result->results[0]->msisdncountrycode);//will get Country code
use this(works with multiple results).
$d = json_decode($content);
foreach($d->results as $row){
echo $row->id; //echoes 21390fb46e92
echo $row->msisdncountrycode; //echoes DE
echo $row->statuscode; //echoes HLRSTATUS_UNDELIVERED
echo $row->hlrerrorcodeid; //echoes 9
}
Echoes are based on current input. Since its in loop, it will print all values.
You can try this. Its working fine for me.
json_decode($content)
Try this:
<?php
$content='{"success":true,"results":[{"id":"21390fb46e92","msisdncountrycode":"DE","msisdn":"+491788735000","statuscode":"HLRSTATUS_UNDELIVERED","hlrerrorcodeid":9,"subscriberstatus":"SUBSCRIBERSTATUS_ABSENT","imsi":null,"mccmnc":"26203","mcc":"262","mnc":"03","msin":null,"servingmsc":null,"servinghlr":null,"originalnetworkname":"E-Plus","originalcountryname":"Germany","originalcountrycode":"DE","originalcountryprefix":"+49","originalnetworkprefix":"178","roamingnetworkname":null,"roamingcountryname":null,"roamingcountrycode":null,"roamingcountryprefix":null,"roamingnetworkprefix":null,"portednetworkname":null,"portedcountryname":null,"portedcountrycode":null,"portedcountryprefix":null,"portednetworkprefix":null,"isvalid":"Yes","isroaming":"No","isported":"No","usercharge":"0.0100","inserttime":"2015-11-24 18:56:42.048693+08","storage":"CURL-TEST","route":"IP1"}]}';
echo '<pre>';
$jsonArr = json_decode($content, TRUE);
$outputArr = $jsonArr['results'][0];
print_r($outputArr);
$id = $outputArr['id'];
$msisdncountrycode = $outputArr['msisdncountrycode'];
$statuscode = $outputArr['statuscode'];
$hlrerrorcodeid = $outputArr['hlrerrorcodeid'];
?>

Convert centimeters (cm) into feets and inches using PHP [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am trying to convert centimeters into feets and inches using PHP.
This is function I use for this calculation.
function getMeasurements($cm) {
$inches = ceil($cm/2.54);
$feet = floor(($inches/12));
$measurement = $feet."' ".($inches%12).'"';
return $measurement;
}
I am calling this function like this :
$cm = 185;
echo "My Height = ".getMeasurements($cm);
Problem is after calling this I can get a result like this-
My Height = 6' 73"
look at inches. Its incorrect. can anybody tell me whats the reason to get such a result.
Thank you.
[akshay#localhost tmp]$ cat test.php
<?php
function cm2feet($cm)
{
$inches = $cm/2.54;
$feet = intval($inches/12);
$inches = $inches%12;
return sprintf('%d ft %d ins', $feet, $inches);
}
echo cm2feet(162)
?>
Output
[akshay#localhost tmp]$ php test.php
5 ft 3 ins
The reason this is happening is that when you run it on phpfiddle.org it is not a true PHP environment. To fix this on phpfiddle, you should add space around your modulus operator.

Need help in DOM traverse using php [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I try to scrape the content post of this forum https://forum.lowyat.net/topic/3424996 using below code.
$rows = $html->find('.post_table');
$array = array();
foreach($rows as $go){
$post_text = $go->find('.post_td_right > .post_text')->innertext;
$array[]= array(
'content'=> $post_text
);
}
echo json_encode($array);
I var_dump($rows) and it's an object, I really don't know why is the mistake. Need your help!
Forums usually have an RSS feed to help with this sort of requirement. Turns out, the site you're scraping supplies this for you: http://rss.forum.lowyat.net/topic/3424996
We can now use an XML parser instead of a DOM scraper, which will be much more efficient. For example;
<?php
$rss = file_get_contents('http://rss.forum.lowyat.net/topic/3424996'); //Or use cURL
$xml = simplexml_load_string($rss);
$array = array();
foreach($xml->channel->item as $posts) {
$post = (array) $posts->description;
$array[] = htmlentities($post[0]);
}
echo "<pre>";
echo print_r($array);
echo "</pre>";

Display 10 array cards [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
http://plnkr.co/edit/06lu6r34eGNfRq1fygNy
I want to only display 10 "cards" from my array, how would I do so?
I tried using unset() but it is very inefficient and doesn't even work for multiple cards.
Also how can I make the code display the "cards" horizontally instead of vertically?
If you’d like to use unset, the correct syntax would be unset($cards[1]); unset($cards[2]); unset($cards[3]); ... and so on.
However, for your particular situation, I’ll recommend you to use array_slice:
$cards = array(
"Messi", "Ronaldo", "Ibrahimovic", "Ribery", "Robben", "Neymar", "Rooney", "Casillas",
"Falcao", "Van Persie", "Hazard", "Iniesta", "Xavi", "Schweinsteiger", "Silva", "Fabregas",
"Lahm", "Aguero", "Cavani", "Vidic", "Ozil", "Mata", "Bale", "ThiagoSilva",
"Kompany", "Tevez", "Toure", "Ramos", "Suarez", "Pirlo", "DiMaria", "Neuer",
"Pique", "Buffon", "Lewandowski", "Gomez", "Chiellini", "Cole", "Pedro", "Busquets",
"Cech", "Muller", "Hummels", "Alonso", "Navas", "Modric", "Cazorla", "Gotze",
"Benzema", "Vidal", "Lavezzi"
);
shuffle($cards);
$cards = array_slice($cards, 0, 10);
For the horizontal display, you may simply omit the <br> at the end of every iteration of your loop, but, depending on the resolution of the user’s browser, the images may occupy more than one line. For a strictly horizontal arrangement, use an HTML table with 10 columns:
print("<table><tr>");
foreach($cards as $card){
$img = "http://d2bm3ljpacyxu8.cloudfront.net/fit/105x97/http://clearpkz.webs.com/webstore/".$card.".png";
print("<td><img src=\"".$img."\"/></td>");
}
print("</tr></table>");
The following works too:
for ($i = 0; $i < 10; $i++) {
echo $cards[$i] ." <br>"; // put the name above the card
echo "<img src='http://d2bm3ljpacyxu8.cloudfront.net/fit/105x97/http://clearpkz.webs.com/webstore/$card.png'> <br>";
}
If you want them horizontally, and without names, don't put in the <br>:
for ($i = 0; $i < 10; $i++) {
echo "<img src='http://d2bm3ljpacyxu8.cloudfront.net/fit/105x97/http://clearpkz.webs.com/webstore/$card.png'>";
}

Categories