I am able to retrieve results from yahoo with my API key, using the instructions found on the yahoo developers website. http://developer.yahoo.com/boss/search/boss_api_guide/codeexamples.html#
Code:
if ($_POST['query'])
{
$newline="<br />";
$query = urlencode("'{$_POST['query']}'");
require("OAuth.php");
$cc_key = "key goes here";
$cc_secret = "secret goes here";
$url = "http://yboss.yahooapis.com/ysearch/web";
$args = array();
$args["q"] = "$query";
$args["format"] = "json";
$consumer = new OAuthConsumer($cc_key, $cc_secret);
$request = OAuthRequest::from_consumer_and_token($consumer, NULL,"GET", $url, $args);
$request->sign_request(new OAuthSignatureMethod_HMAC_SHA1(), $consumer, NULL);
$url = sprintf("%s?%s", $url, OAuthUtil::build_http_query($args));
$ch = curl_init();
$headers = array($request->to_header());
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
$rsp = curl_exec($ch);
$results = json_decode($rsp);
print_r($results);
}
Using print_r($results) as shown above, I get results, such as the following (extract of first three results shown from searching for "elephant"):
PLEASE NOTE I HAVE CHANGED THE URLS TO "WWW" AS I REQUIRE AT LEAST 10 REPUTATION TO POST MORE THAN 2 LINKS.
stdClass Object ( [bossresponse] => stdClass Object ( [responsecode]
=> 200 [web] => stdClass Object ( [start] => 0 [count] => 50 [totalresults] => 36800000 [results] => Array ( [0] => stdClass Object
( [date] => [clickurl] => WWW [url]
=> WWW [dispurl] => en.wikipedia.org/wiki/Elephant [title] => Elephant - Wikipedia, the
free encyclopedia [abstract] => Elephant trunks have multiple
functions, including breathing, olfaction, ... One elephant has been
observed to graze by kneeling on its front legs, ... ) [1] => stdClass
Object ( [date] => [clickurl] =>
WWW [url] =>
WWW [dispurl] =>
www.defenders.org/elephant/basic-facts [title] => Elephant | Basic
Facts About Elephants | Defenders of Wildlife [abstract] => Elephant.
Basic Facts About Elephants More on Elephant: Threats to Elephants ยป
More on Elephant: Basic Facts . Threats. What Defenders Is Doing to
Help. What You Can ... ) [2] => stdClass Object ( [date] => [clickurl]
=> WWW
[url] =>
WWW
[dispurl] => kids.nationalgeographic.com/.../african-elephant [title]
=> African Elephant Facts and Pictures -- National Geographic Kids [abstract] => Kids' feature about elephants, with photographs, video,
audio, fun facts, an e-mail postcard, and links to other animals. )
[3] => stdClass Object ( [date] => [clickurl] =>
WWW [url]
=> WWW [dispurl] => elephant.elehost.com/About_Elephants/about_elephants.htm
[title] => About Elephants [abstract] => All about elephants on the
Elephant Information Repository! This page includes a summary of
elephant related facts to get you inducted in to the world of
elephants. )
I have attempted to output the results, in a legible format, as follows:
Code Attempt 1:
foreach ($results->{ 'results' } as $item )
{
echo "<font color ='blue'>{$item->{ 'title' }}</font>".": "."$newline"."$newline".$item->{ 'abstract' }."\n\n";
}
I also tried the following, without success:
Code Attempt 2:
echo $results['results']['url'];
echo $results['results']['title'];
echo $results['results']['abstract'];
Any ideas on what to do?
Thanks.
I've noticed you just copy-pasted the code from the documentation's code examples, but never mind that.
You're accessing the results array the wrong way:
foreach ($results->bossresponse->web->results as $result)
{
//do stuff
echo $result->title.'<br/>';
}
Or, as cptnk suggested:
$results = json_decode($rsp, true);
//force to assoc-array, which will allow array-access
foreach($results['bossresponse']['web']['results'] as $result)
{
//$result is array here, but do the same stuff
echo $result['title'].'<br/>';
}
Or, combine the two
foreach($results->bossresponse->web->results as $result)
{
$result = (array) $result;//casts stdClass to array
printf('%s<br/>', $result['url'], $result['title']);
}
Related
I have an array returned from a json, I can access the values from one part of the array, but I can't access the values from another part of the array
echo '<strong>Barcode Number:</strong> ' . $response->products[0]->barcode_number . '<br><br>';
echo '<strong>Product Name:</strong> ' . $response->products[0]->product_name . '<br><br>';
echo '<strong>Description:</strong> ' . $response->products[0]->description . '<br><br>';
echo '<strong>Description:</strong> ' . $response->stores[0]->store_name . '<br><br>';
I get the first three fine but the last one for stores returns the error
Barcode Number: 077341125112
Product Name: Custom Accessories 89960W E-Tek Butane Torch
Description: Butane Torch, 89960W is ideal for your home garage or
your car. Can be used for quick repairs.
Notice: Undefined property: stdClass::$stores in
C:\xampp\htdocs\customs\production\test-barcodelookup.php on line 20
Notice: Trying to get property 'store_name' of non-object in
C:\xampp\htdocs\customs\production\test-barcodelookup.php on line 20
$ch = curl_init(); // Use only one cURL connection for multiple queries
$data = get_data($url, $ch);
$response = array();
$response = json_decode($data);
echo '<strong>Barcode Number:</strong> ' . $response->products[0]->barcode_number . '<br><br>';
echo '<strong>Product Name:</strong> ' . $response->products[0]->product_name . '<br><br>';
echo '<strong>Description:</strong> ' . $response->products[0]->description . '<br><br>';
echo '<strong>Description:</strong> ' . $response->stores[0]->store_name . '<br><br>';
echo '<strong>Entire Response:</strong><pre>';
print_r($response);
echo '</pre>';
function get_data($url, $ch) {
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
Below is the array returned
Entire Response:
stdClass Object
(
[products] => Array
(
[0] => stdClass Object
(
[barcode_number] => 077341125112
[barcode_type] => UPC
[barcode_formats] => UPC 077341125112, EAN 0077341125112
[mpn] => 0007734112511
[model] => 89960w
[asin] =>
[product_name] => Custom Accessories 89960W E-Tek Butane Torch
[title] =>
[category] => Hardware > Tools > Hardware Torches
[manufacturer] =>
[brand] => Etek
[label] =>
[author] =>
[publisher] =>
[artist] =>
[actor] =>
[director] =>
[studio] =>
[genre] =>
[audience_rating] =>
[ingredients] =>
[nutrition_facts] =>
[color] =>
[format] =>
[package_quantity] =>
[size] =>
[length] =>
[width] =>
[height] =>
[weight] =>
[release_date] =>
[description] => Butane Torch, 89960W is ideal for your home garage or your car. Can be used for quick repairs.
[features] => Array
(
)
[images] => Array
(
[0] => https://images.barcodelookup.com/3001/30014169-1.jpg
)
[stores] => Array
(
[0] => stdClass Object
(
[store_name] => Wal-Mart.com USA, LLC
[store_price] => 14.97
[product_url] => http://www.walmart.com/ip/Custom-Accessories-89960W-E-Tek-Butane-Torch/29029306
[currency_code] => USD
[currency_symbol] => $
)
[1] => stdClass Object
(
[store_name] => Jet.com
[store_price] => 14.20
[product_url] => http://jet.com/product/detail/a43035df304c4551b45f62262402f9f2
[currency_code] => USD
[currency_symbol] => $
)
)
[reviews] => Array
(
[0] => stdClass Object
(
[name] => Ken Weber
[rating] => 5
[title] => Torch Performance
[review] => I didnt know how good this torch was until I used it and its very nice for the money. The electronic ignition fires the butane evertime. Nice feel to it. Has a trigger lock down for extended usage time. GOOD PRODUCT.
[datetime] => 2015-12-29 11:27:34
)
)
)
)
)
I am trying to access the images array and echo it out and the information from the stores array and echo it. I can get the information from the products array. but I can't figure out how to get the others
This is what I am trying to achieve
Barcode Number: 077341125112
Product Name: Custom Accessories 89960W E-Tek Butane Torch
Description: Butane Torch, 89960W is ideal for your home garage or
your car. Can be used for quick repairs.
Display Image of product.
Stores:
store_name: Wal-Mart.com USA, LLC store_price: 14.97 product_url:
http://www.walmart.com/ip/Custom-Accessories-89960W-E-Tek-Butane-Torch/29029306
store_name: Jet.com store_price: 14.20 product_url:
http://jet.com/product/detail/a43035df304c4551b45f62262402f9f2
When you format the data, it shows that the stores data is under each product, so you would need to display it as...
$response->products[0]->stores[0]->store_name
You would also probably need to use a foreach() to display all the details, both with products and the stores for each product.
foreach ( $response->products[0]->stores as $store ) {
// Echo out the details
echo $store->store_name;
}
Side-step: I think the easiest way to go about this process is using
json_decode($json, true);
This makes everything an associative array.
Here is the manual for the json_decode internal function.
Step-back:
$response->products[0]->stores[0]->store_name
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 5 years ago.
Improve this question
I have the really complex array:
stdClass Object
(
[matters] => Array
(
[0] => stdClass Object
(
[id] => 1050370768
[client] => stdClass Object
(
[id] => 939940280
[url] => /api/v2/contacts/939940280
[name] => Balter and Son
)
[display_number] => 00001-Balter and Son
[description] => Sueing for pain of having to program
[status] => Open
[open_date] => 2017-07-26
[close_date] =>
[pending_date] =>
[location] =>
[client_reference] => 34241
[responsible_attorney] => stdClass Object
(
[id] => 345011996
[url] => /api/v2/users/345011996
[name] => jon balter
[email] => jbalter#seamlesssolutions.com
)
[originating_attorney] =>
[practice_area] =>
[billable] => 1
[maildrop_address] => ecd6d7b60+matter1050370768#maildrop.clio.com
[created_at] => 2017-07-26T20:46:14+00:00
[updated_at] => 2017-07-26T20:46:14+00:00
[custom_field_values] => Array
(
)
[billing_method] => hourly
[group_id] => 1654280
[permission] => stdClass Object
(
[id] => 1654280
[url] => /api/v2/groups/1654280
[name] => Firm
)
[activity_rates] => Array
(
)
)
[1] => stdClass Object
(
[id] => 1050770508
[client] => stdClass Object
(
[id] => 940983330
[url] => /api/v2/contacts/940983330
[name] => Seamless Solutions
)
[display_number] => 00002-Seamless Solutions
[description] => This is a matter of life and death
[status] => Open
[open_date] => 2017-08-09
[close_date] =>
[pending_date] =>
[location] =>
[client_reference] =>
[responsible_attorney] =>
[originating_attorney] =>
[practice_area] =>
[billable] => 1
[maildrop_address] => ecd6d7b60+matter1050770508#maildrop.clio.com
[created_at] => 2017-08-09T21:37:28+00:00
[updated_at] => 2017-08-09T21:37:28+00:00
[custom_field_values] => Array
(
)
[billing_method] => hourly
[group_id] => 1654280
[permission] => stdClass Object
(
[id] => 1654280
[url] => /api/v2/groups/1654280
[name] => Firm
)
[activity_rates] => Array
(
)
)
)
[records] => 2
[limit] => 200
[next_offset] => 1050770508
[order_dir] => asc
[total_records] => 2
[published_at] => 2017-08-09T21:37:38+00:00
)
I just want to get a return of
Array (
[display_number] => 00001-Balter and Son
[display_number] => 00002-Seamless Solutions
)
Then take this and save this as a CSV
00001,Balter and Son,
00002,Seamless Solutions
Any help would be awesome.
I know there has to be an easy way to do this.
Someone asked for the PHP. Little hard to put here but I will try. It is part of an API for CLIO legal software.
//Get Matters
$matterarry = matter_numbers ($token);
//get array to just matter numbers
$matternumbers = array(); // initialize the array to be used for the export
foreach($matterarry->matters as $key => $matter) { // loop through all the top level element
// isolate the display number '00001' from '00001-Balter and Son'
$displayNumber = explode('-', $matter->display_number);
$displayNumber = $displayNumber[0];
// push the element the export array using the display_number as the key
$matternumbers[$key] = array(
$displayNumber, // '00001'
$matter->client->name // 'Balter and Son'
);
}
Print_r ($matternumbers);
//export to CSV
$f = fopen('/tmp/matternumbers.csv', 'a'); // open the destination file handler
fputcsv($f, array('display_number', 'name')); // start by adding the column headers
// this can also be done by using named keys in your array,
// or having the first element be the value of the headers
// I'm appending manually here for the sake of simplicity
foreach($matternumbers as $key => $element) {
fputcsv($f, $element); // append each element to the file
}
fclose($f); // don't forget to close the file ;)
function matter_numbers ( $token ) {
//$header = array('Authorization: bearer '.$token);
//print_r ($header);
$header = 'Authorization: bearer '.$token;
echo $header."\r\n";
$ch = curl_init();
//curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_URL, 'https://app.goclio.com/api/v2/matters');
curl_setopt($ch, CURLOPT_HTTPHEADER, array($header));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$resp = curl_exec($ch);
if( !$resp ) {
die('Error: "' . curl_error( $ch ) . '" - Code: ' . curl_errno( $ch ) );
}
else if ( 200 != curl_getinfo( $ch, CURLINFO_HTTP_CODE ) ) {
echo "Bad Response Code!";
echo "\n";
echo "Response HTTP Status Code : " . curl_getinfo( $ch, CURLINFO_HTTP_CODE );
echo "\n";
echo "Response HTTP Body : " . $resp;
}
//print "curl response is:" . $resp;
$resp = json_decode($resp);
//print_r ($resp);
curl_close($ch);
return $resp;
}
I'll try addressing the two parts of your question (1) simplifying the array to isolate specific elements and (2) exporting that to a .csv file
Simplifying the array
For this you'll need to iterate over all the matters element of your original object and push whatever value(s) you wish to export in a new array with the appropriate format
$exportArray = array(); // initialize the array to be used for the export
foreach($initialObject->matters as $key => $matter) { // loop through all the top level element
// isolate the display number '00001' from '00001-Balter and Son'
$displayNumber = explode('-', $matter->display_number);
$displayNumber = $displayNumber[0];
// push the element the export array using the display_number as the key
$exportArray[$key] = array(
$displayNumber, // '00001'
$matter->client->name // 'Balter and Son'
);
}
You then end up with an array that should look a little something like that:
Array [
0 => Array [
0 => '00001'
1 => 'Balter and Son'
]
1 => Array [
0 => '00002'
1 => 'Seamless solutions'
]
]
Alternatively, instead of looping over the array you could use array_map() and obtain a similar result. If you're not familiar with array_map() you can find the official doc here
$exportArray = array_map(function($matter) {
// isolate the display number '00001' from '00001-Balter and Son'
$displayNumber = explode('-', $matter->display_number);
$displayNumber = $displayNumber[0];
return array(
$displayNumber,
$matter->client->name
);
}, $initialObject->matters)
Exporting to CSV
This part is actually quite easy as PHP has a function specifically for this (Official Doc)
$f = fopen('/tmp/myFile.csv', 'a') // open the destination file handler
fputcsv($f, array('display_number', 'name')) // start by adding the column headers
// this can also be done by using named keys in your array,
// or having the first element be the value of the headers
// I'm appending manually here for the sake of simplicity
foreach($exportArray as $key => $element) {
fputcsv($f, $element); // append each element to the file
}
fclose($f) // don't forget to close the file ;)
Mixing the two together
Looping over the elements you want to export twice is tedious and will affect readability and maintainability. This is why you should probably mix those examples together in a single loop.
$file = fopen('/tmp/myFile.csv', 'a'); // open the destination file handler
fputcsv($file, array('display_number', 'name')); // add the column headers
foreach($initialObject->matters as $key => $matter) { // loop through all the top level element
// isolate the display number '00001' from '00001-Balter and Son'
$displayNumber = explode('-', $matter->display_number);
$displayNumber = $displayNumber[0];
// Add the information you need directly in the file
fputcsv($file, array($displayNumber, $matter->client->name));
}
fclose($file);
For the sake of simplicity, I have assumed that your destination file is empty. If you don't know how to make sure a file is empty before starting working with, I suggest you look at this question that sums it up very well.
I've been working on this SoundCloud website for awhile now and have just got into creating a stream page alternative that will display on our website. I have stumbled into an issue however and I'm sure it's an easy solution I'm just now figuring out how 2 achieve the proper output.
$user_ID = $_GET['id'];
$sc = curl_init();
curl_setopt($sc, CURLOPT_URL, 'http://api.soundcloud.com/users/'.$user_ID.'/followings?client_id='.$client_ID.'&page_size=200&cursor=1419617528000');
curl_setopt($sc, CURLOPT_HEADER, 0);
curl_setopt($sc, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($sc);
curl_close($sc);
$content = json_decode($output, true);
As you can see above the code currently is suppose to display up to 400 users in which someone is following, however when we do the following 2 return all of the content which is being displayed on that link.
echo "<pre>";
print_r($content);
echo "</pre>";
It appears that it caps at only 200 results ( which is really not that good we need 2 find an alternative 2 display the full amount of users someone is following. ) at the bottom of th page it displays another message.
[199] => Array
(
[avatar_url] => http://a1.sndcdn.com/images/default_avatar_large.png?1485508269
[id] => 72067899
[kind] => user
[permalink_url] => http://soundcloud.com/berthalie30
[uri] => https://api.soundcloud.com/users/72067899
[username] => berthalie30
[permalink] => berthalie30
[last_modified] => 2016/04/06 21:53:03 +0000
[first_name] =>
[last_name] =>
[full_name] =>
[city] =>
[description] =>
[country] =>
[track_count] => 0
[public_favorites_count] => 0
[followers_count] => 21
[followings_count] => 89
[plan] => Free
[myspace_name] =>
[discogs_name] =>
[website_title] =>
[website] =>
[reposts_count] => 32
[comments_count] => 0
[online] =>
[likes_count] => 0
[playlist_count] => 6
)
)
[next_href] => https://api.soundcloud.com/users/24537746/followings?client_id=XXXX&page_size=200&cursor=1406526915000
However, even using this method does nothing (even though I'm more then certain the user I am testing with has more then 200 users he's following.)
EDIT : Someone here is having the same issue, how ever I don't understand the comment solution on how 2 prevent it from happening..
Can someone please help me to print this data using tables or css or bootstrap..?
PHP Code Used:
$url = "http://some-website.com/api/message";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$content = curl_exec($ch);
curl_close($ch);
$json = json_decode($content, true);
$count=count($json);
print_r ($json);
Result:
Array
(
[success] => 1
[result] => Array
(
[0] => Array
(
[id] => 12491055
[device_id] => 18398
[message] => hi there!
[status] => received
[send_at] => 0
[queued_at] => 0
[sent_at] => 0
[delivered_at] => 0
[expires_at] => 0
[canceled_at] => 0
[failed_at] => 0
[received_at] => 1456228673
[error] => N/A
[created_at] => 1456271873
[contact] => Array
(
[id] => 3077686
[name] => charan
[number] => 123456789
)
)
)
)
I'm new in this php field so don't try to make your answers bit difficult one for me to understand or execute.
i want it to be printed like:
Name: some one
Message: Hi
Etc.........
just like online desposal mobile numbers & message's services sites
Thanks In Advance!
Just look at the array you already have, and drill down.
echo "Name: " . $json['result'][0]['contact']['name'];
Or:
echo "Message: " . $json['result'][0]['message'];
use foreach() to print your array.example:
$tab=array('name'=>'Jack','last name'=>'sparrow');
foreach($tab as $key=>$elem)
{
echo "$key : $elem <br>";
}
//the result
//name: jack
//last name : sparrow
I am getting this json output from yahoo boss api. It goes on for 50 results, but, I have pasted only the first two...
(
[bossresponse] => stdClass Object
(
[responsecode] => 200
[web] => stdClass Object
(
[start] => 0
[count] => 50
[totalresults] => 2750000
[results] => Array
(
[0] => stdClass Object
(
[date] =>
[clickurl] => http://www.apple.com/ipad/
[url] => http://www.apple.com/ipad/
[dispurl] => www.apple.com/<b>ipad</b>
[title] => Apple - <b>iPad</b>
[abstract] => <b>iPad</b> is a magical window where nothing comes between you and what you love. And it comes in two sizes.
)
[1] => stdClass Object
(
[date] =>
[clickurl] => http://en.wikipedia.org/wiki/IPad
[url] => http://en.wikipedia.org/wiki/IPad
[dispurl] => en.wikipedia.org/wiki/<b>IPad</b>
[title] => <b>iPad</b> - Wikipedia, the free encyclopedia
[abstract] => The <b>iPad</b> is a line of tablet computers designed and marketed by Apple Inc., which runs Apple's iOS operating system. The first <b>iPad</b> was released on April 3, 2010; the ...
)
[2] => stdClass Object
(
[date] =>
[clickurl] => http://www.amazon.com/s?ie=UTF8&page=1&rh=i%3Aaps%2Ck%3Aipad
[url] => http://www.amazon.com/s?ie=UTF8&page=1&rh=i%3Aaps%2Ck%3Aipad
[dispurl] => www.amazon.com/s?ie=UTF8&page=1&rh=i%3Aaps%2Ck%3A<b>ipad</b>
[title] => Amazon.com: <b>ipad</b>
[abstract] => Considering an <b>iPad</b>? Compare it to Kindle Fire HD Check out our easy side-by-side comparison chart to see how the newest <b>iPad</b> stacks up to Kindle Fire HD 8.9".
)
I use the following code in php to connect to the api and display the results...
**//connect to yahoo api and get results in json**
<?php
require("OAuth.php");
$cc_key = "**confidential**";
$cc_secret = "**confidential**";
$url = "http://yboss.yahooapis.com/ysearch/web";
$args = array();
$args["q"] = "yahoo";
$args["format"] = "json";
$consumer = new OAuthConsumer($cc_key, $cc_secret);
$request = OAuthRequest::from_consumer_and_token($consumer, NULL,"GET", $url, $args);
$request->sign_request(new OAuthSignatureMethod_HMAC_SHA1(), $consumer, NULL);
$url = sprintf("%s?%s", $url, OAuthUtil::build_http_query($args));
$ch = curl_init();
$headers = array($request->to_header());
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$rsp = curl_exec($ch);
$results = json_decode($rsp);
?>
**// Present results in html/php**
<div id="resultsdiv">
<?php
foreach($results->bossresponse->web->results as $result)
{
echo '<h3><a href='.$result->url.'>'.$result->title.'</br>'.$result->abstract.'</a></h3>';
}
?>
My question is how do I paginate results, since all the 50 results appear on the first web page only. I want to display ten results in every page.
Any help is appreciated.
Thanks.
According to the Yahoo! BOSS documentation, specifically the Universal Arguments section, it looks like you can use the start and count parameters to adjust the pagination of results. It looks like the default return count is 50 which matches what you observed.
In your code example you can adjust by adding:
$args["start"] = 0; // increment as needed
$args["count"] = 10;