Using curl to load next json page results in php - php

I'm using PHP and cURL to retrieve API information from a website. I have a loop to display all the information on my page which works just fine. The problem I'm having is, my results page displays 10 items per page. The API offers pagination in which it provides me with the next page link url to page 2, 3, and so forth. I cannot find for the life of me, how to make this next link load page 2 information and display it on the same page(it sounds easy enough). I have tried numerous different techniques and none have worked so far. I'm currently stuck where page 1 loads and displays page 1 and 2 data. I would like to have it to where you click the next link and it refreshes the page with your page 2 data and removes page 1 data. Any help is greatly appreciated...Here is my current code...
<section>
<form method="post" action="<?php echo $PHP_SELF;?>" id="searchForm">
<input type="text" name="searchText" id="searchText" placeholder="e.g. Haze.." value=""/><br>
<button type="submit" name="submit" id="searchButton" form="searchForm">Search</button>
<?php
if (isset($_POST['submit'])){
$url = 'https://www.cannabisreports.com/api/v1.0/strains/search/:' . urlencode ($_POST["searchText"]);
$curl = curl_init();
curl_setopt ($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('X-API-Key : XXXXXXXXXXXXXXXXXXXXXXXX'));
curl_setopt ($curl, CURLOPT_RETURNTRANSFER, 1 );
$result = curl_exec($curl);
curl_close($curl);
$jsonobj = json_decode($result);
echo('<ul id="resultList">');
foreach($jsonobj->data as $value)
{
echo('<li class="resultListItem">');
echo('<img src="' . $value->image . '">');
echo '<br>';
echo $value->seedCompany->name;
echo '<br>';
echo $value->genetics->names;
echo '<br>';
echo $value->reviews->count;
echo("</li>");
}
echo("</ul>");
//********code for next page
echo(' Next ');
if(isset($_GET['nextPage'])) {
header('location: http://www.strains.blazedmaps.com ');
$urlNext = $jsonobj->meta->pagination->links->next;
$curlNext = curl_init();
curl_setopt ($curlNext, CURLOPT_URL, $urlNext);
curl_setopt ($curlNext, CURLOPT_HTTPheader, array('X-API-Key : XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'));
curl_setopt ($curlNext, CURLOPT_RETURNTRANSFER, 1 );
$resultNext = curl_exec($curlNext);
curl_close($curlNext);
$jsonobjNext = json_decode($resultNext);
echo('<ul id="resultList">');
foreach($jsonobjNext->data as $value1)
{
echo('<li class="resultListItem">');
echo('<img src="' . $value1->image . '">');
echo '<br>';
echo $value1->seedCompany->name;
echo '<br>';
echo $value1->genetics->names;
echo '<br>';
echo $value->reviews->count;
echo("</li>");
}
echo("</ul>");
}
}
?>
</form>
</section>

Related

Looping JSON data only shows the first character

I am trying to output specific information coming from JIRA, I have JSON looping and results showing, but the results furthest down the nest are only showing the first character.
I have tried following the suggestions here but this seems to be for results at the top level and I can't seem to get it working with my code.
<?php
$username = '*************';
$password = '*************';
$url = '<JIRA-DOMAIN>/rest/api/2/search?jql=project=ICI&fields=key,summary,description&maxResults=10';
$curl = curl_init();
curl_setopt($curl, CURLOPT_USERPWD, "$username:$password");
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
$issue_list = (curl_exec($curl));
$json = json_decode($issue_list, TRUE);
?>
<div class="toto">
<?php
foreach($json['issues'] as $obj){ ?>
<h2><?php echo $obj['id']; ?></h2>
<?php foreach($obj['fields'] as $parc){ ?>
<a href="<?php echo $parc['summary']; ?>">
<span><?php echo $parc['description']; ?></span>
</a>
<?php }
} ?>
</div>
When I echo $issue_list I get the following:
Output Shortened
{
"expand":"schema,names",
"startAt":0,
"maxResults":10,
"total":9,
"issues":[
{
"expand":"operations,versionedRepresentations,editmeta,changelog,renderedFields",
"id":"10058",
"self":"<domain>/rest/api/2/issue/10058",
"key":"ICI-9",
"fields":{
"summary":"ToS and PP button removal",
"description":"The Terms of Service and Privacy Policy buttons go to a page on the website so they can't use the app after. They also go to a page of nothing because they aren't written so they need to be deleted"
}
},
{
"expand":"operations,versionedRepresentations,editmeta,changelog,renderedFields",
"id":"10048",
"self":"<domain>/rest/api/2/issue/10048",
"key":"ICI-1",
"fields":{
"summary":"Create Launch Image",
"description":"Create launch image for app. Resolution should be: 2048px × 1536px\r\n\r\n[~james.whitaker] I got this info from [here|https://developer.apple.com/design/human-interface-guidelines/ios/icons-and-images/launch-screen/]"
}
}
]
}
But the loop output only shows the first character for the Description and Summary as seen below but shows the entire ID.
Any help would be highly appreciated.
Your problem is in this foreach loop:
<?php foreach($obj['fields'] as $parc){ ?>
<a href="<?php echo $parc['summary']; ?>">
<span><?php echo $parc['description']; ?></span>
</a>
<?php }
$parc will have the value of $obj['fields']['summary'] and then $obj['fields']['description'] in the loop, so when you try and index it with ['summary'] you are using an invalid index which is translating to 0 (hence the single character). Try this instead (remove the foreach):
<a href="<?php echo $obj['fields']['summary']; ?>">
<span><?php echo $obj['fields']['description']; ?></span>
</a>
i think fields isn't array.
Change $parc['summary'] to $obj['fields']['summary']

php file get contents not working while fetching fb page data

I have the following code to get fb page list
$graph_url_pages = "https://graph.facebook.com/me/accounts?access_token=".$_SESSION['token'];
$pagedata=file_get_contents($graph_url_pages);
echo "DATA : <br>";
print_r($pagedata);
$pages=json_decode($pagedata,true);
var_dump($pages);
$dropdown = "";
for($i=0;$i<count($pages->data);$i++)
{
if($me=="iamindex"){
$dropdown .= "<option value='".$pages->data[$i]->access_token."-".$pages->data[$i]->id."'>".$pages->data[$i]->name."</option>";
}elseif($me=="iammulti"){
$dropdown .= "<input type='checkbox' name='page' id='status' value='".$pages->data[$i]->access_token."-".$pages->data[$i]->id."'>".$pages->data[$i]->name."<br>";
}else{$dropdown.="<option value=''>No Category Selection</option>";}
}
$pagedata and $pages is empty and so dropdown doesn't get populated.
Somewhere at the top of the page I am using Ob_start() and at the end Ob_flush(); And they are needed. I don't know whether this is the issue.
Would be great if somebody can point out what is going wrong ! if more code is needed, I can provide. Please note I am an amateur programmer. Self taught.
I recommend using cURL
$graph_url_pages = "https://graph.facebook.com/me/accounts?access_token=".$_SESSION['token'];
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $graph_url_pages);
if(curl_error($c))
{
echo 'error:' . curl_error($c);
//it will produce the error if any exists
}
$data = curl_exec($ch);
curl_close($ch);
print_r($data);

PHP DOM parser breaks the page and can't load page content

I have created a php parser that must extract the price in a span tag, but when I echo the $html so that I could see how the page loads, it shows me a broken page with no contents. Instead only header and footer loads, but not the content. The content seems to load by JavaScript externally and my question is how can I load the html page with Dom so that JavaScript also loads? I need to let the whole content load so that I can get the divs and spans. This is my code:
<?php
require_once('simple_html_dom.php');
$url = 'http://oldnavy.gap.com/browse/product.do?cid=99570&vid=1&pid=714649002';
$dom = new domDocument('1.0', 'UTF-8');
$html = file_get_html($url);
echo $html;
if(is_object($html)){
foreach ( $html->find('span#priceText') as $data){
$raw_price = $data->innertext;
echo $raw_price;
}
}
?>
Alt aproach
The link you are actually looking for (in his minimal expression) is this: http://oldnavy.gap.com/browse/productData.do?pid=714649
Now load that using curl, put a value to the unknownShopperId cookie, explode it into an array and get the price you need:
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, "http://oldnavy.gap.com/browse/productData.do?pid=714649");
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Cookie: unknownShopperId=E853DA3B2607DDAA5F2FE13CE8D32ACF"));
$result = curl_exec($ch);
$explode = explode(',', $result);
echo 'Original price: ' . $explode[92] . '<br/>' .
'New price: ' . $explode[93] . '<br/>' .
'Both prices: ' . $explode[13];
The result will be: '$14.94'
From now on, if you need another price you must know the intem's pid

PHP Output (json)

This is my script which is fetching a delivery report form my service providers api & displaying it in json format. I want this to be displayed in a table form using the mobile & status fields.
<?php
$uid="UID";
$pin="PIN";
$domain="DOMAIN";
$route="5";
$method="POST";
$rtype="json";
//---------------------------------
if(isset($_REQUEST['send']))
{
$date=$_REQUEST['date'];
$uid=urlencode($uid);
$pin=urlencode($pin);
$rtype=urlencode($rtype);
$route=urlencode($route);
$date=urlencode($date);
$rtype=urlencode($rtype);
$parameters="uid=$uid&pin=$pin&date=$date&route=$route&rtype=$rtype";
$url="http://$domain/api/dlr.php";
$ch = curl_init($url);
if($method=="POST")
{
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$parameters);
}
else
{
$get_url=$url."?".$parameters;
curl_setopt($ch, CURLOPT_POST,0);
curl_setopt($ch, CURLOPT_URL, $get_url);
}
curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);
curl_setopt($ch, CURLOPT_HEADER,0); // DO NOT RETURN HTTP HEADERS
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); // RETURN THE CONTENTS OF THE CALL
$return_val = curl_exec($ch);
if($return_val=="")
echo "Process Failed, Please check your connecting domain, username or password.";
else
echo "$return_val";
}
echo "<form name='f1' method='post'>";
echo "<p> Date (##-##-####): <input name='date' > </p>";
echo "<p> <input type='submit' value='Send' name='send'></p>";
echo "</form";
?>
OUTPUT
[{"smsid":"211677113","mobile":"9876546577","status":"Delivered"},{"smsid":"211677166","mobile":"98765454377","status":"Delivered"}]
try json_decode()
$str = json_decode('[{"smsid":"211677113","mobile":"9876546577","status":"Delivered"},{"smsid":"211677166","mobile":"98765454377","status":"Delivered"}]', true);
print_r($str);
it will convert your json string in an array then loop through your array and print output as you wish like
foreach($str as $k=>$v) {
echo $v['smsid'];
echo $v['mobile'];
echo $v['status'];
}
Try to show table
<?php
$a = json_decode('[{"smsid":"211677113","mobile":"9876546577","status":"Delivered"},{"smsid":"211677166","mobile":"98765454377","status":"Delivered"}]');
?>
<table border="1">
<?php
foreach($a as $k=>$v){?>
<tr>
<td><?=$v->mobile?></td>
<td><?=$v->status?></td>
</tr>
<?php } ?>
</table>

Load page and submit form inside PHP

I'm creating an system that uses online compiler. IDEONE give me this feature (throgh an Web Service), but with a price for an high volume of compilations.
Then I'm trying to use codepad, but it doesn't have an Web Service... codepad has an initial page, and clicking it's submit button, apparently the same page loads (the form's action is "/")...
I'm using curl to load page, but I'm getting "Internal Server Error". This is my code: pastebin Code, I'm using 000webhost, I don't know if i did something wrong or if my webserver doesn't support it.
Have you trued removing the TIMEOUT? or maybe extending it?
Try this maybe:
<html>
<div align="center">
<form action="compilador.php" method="POST">
<textarea id="source" name="source"></textarea>
<input type="submit" value="Enviar" />
<?php
if(isset($_POST['source']) && $_POST['source'] != "")
{
$ch = curl_init();
/**
* Set the URL of the page or file to download.
*/
curl_setopt($ch, CURLOPT_URL, "http://codepad.org");
/**
* Ask cURL to return the contents in a variable instead of simply echoing them to the browser.
*/
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$post_data=$_POST;
$post_data['lang'] = 'C';
$post_data['private'] = True;
$post_data['run'] = True;
foreach($post_data as $key => $value)
{
$post_items[] = $key . '=' . $value;
}
$post_string = implode ('&', $post_items);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
$result = curl_exec ($ch);
/**
* Close cURL session
*/
curl_close($ch);
echo "<br /><br />RESULT: {".$result."}";
}
?>
</form>
</div>
</html>

Categories