Accessing object properties? Google API - php

<?PHP
$ip = $_SERVER['REMOTE_ADDR'];
$searchterm = str_replace(' ', '%20', $_POST["searchterm"]);
if(isset($_POST["submit"])){
// The request also includes the userip parameter which provides the end
// user's IP address. Doing so will help distinguish this legitimate
// server-side traffic from traffic which doesn't come from an end-user.
$url = "https://ajax.googleapis.com/ajax/services/search/web?v=1.0&"
. "q=".$searchterm."&userip=".$ip;
// sendRequest
// note how referer is set manually
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_REFERER, bla.myserver.net);
$body = curl_exec($ch);
curl_close($ch);
// now, process the JSON string
$json = json_decode($body);
// now have some fun with the results...
}
?>
<form method="POST" action="<?PHP $_SERVER["PHP_SELF"]; ?>">
<p><input type="text" name="searchterm"></p>
<p><input type="submit" name="submit"></p>
</form>
<?PHP
if(isset($_POST["submit"])){
print_r($json);
$jsonNew = $json->{'results'};
print_r($jsonNew);
}
?>
The output for the variable $json is
stdClass Object ( [responseData] => stdClass Object ( [results] => Array ( [0] => stdClass Object ( [GsearchResultClass] => GwebSearch [unescapedUrl] => http://www.speedtest.net/ [url] => http://www.speedtest.net/ [visibleUrl] => www.speedtest.net [cacheUrl] => http://www.google.com/search?q=cache:M47_v0xF3m8J:www.speedtest.net [title] => Speedtest.net by Ookla - The Global Broadband Speed Test [titleNoFormatting] => Speedtest.net by Ookla - The Global Broadband Speed Test [content] => Test your Internet connection bandwidth to locations around the world with this interactive broadband speed test from Ookla. ) [1] => stdClass Object ( [GsearchResultClass] => GwebSearch [unescapedUrl] => https://www.test.com/ [url] => https://www.test.com/ [visibleUrl] => www.test.com [cacheUrl] => http://www.google.com/search?q=cache:S92tylTr1V8J:www.test.com [title] => Platform to Create Organizational Testing and Certifications [titleNoFormatting] => Platform to Create Organizational Testing and Certifications [content] => Test.com is a software solution for you to easily create, administer and manage training courses and certification tests, in up to 22 languages. ) [2] => stdClass Object ( [GsearchResultClass] => GwebSearch [unescapedUrl] => https://en.wikipedia.org/wiki/Test [url] => https://en.wikipedia.org/wiki/Test [visibleUrl] => en.wikipedia.org [cacheUrl] => http://www.google.com/search?q=cache:R94CAo00wOYJ:en.wikipedia.org [title] => Test - Wikipedia, the free encyclopedia [titleNoFormatting] => Test - Wikipedia, the free encyclopedia [content] => Test, TEST or Tester may refer to: Test (assessment), an assessment intended to measure the respondents' knowledge or other abilities ... ) [3] => stdClass Object ( [GsearchResultClass] => GwebSearch [unescapedUrl] => https://www.speakeasy.net/speedtest/ [url] => https://www.speakeasy.net/speedtest/ [visibleUrl] => www.speakeasy.net [cacheUrl] => http://www.google.com/search?q=cache:sCEGhiP0qxEJ:www.speakeasy.net [title] => Speakeasy Speed Test - Powered by MegaPath [titleNoFormatting] => Speakeasy Speed Test - Powered by MegaPath [content] => Speakeasy, a MegaPath Brand, offers industry leading business voice, data and IT solutions. We ensure the speed, performance and reliability of all our ... ) ) [cursor] => stdClass Object ( [resultCount] => 258,000,000 [pages] => Array ( [0] => stdClass Object ( [start] => 0 [label] => 1 ) [1] => stdClass Object ( [start] => 4 [label] => 2 ) [2] => stdClass Object ( [start] => 8 [label] => 3 ) [3] => stdClass Object ( [start] => 12 [label] => 4 ) [4] => stdClass Object ( [start] => 16 [label] => 5 ) [5] => stdClass Object ( [start] => 20 [label] => 6 ) [6] => stdClass Object ( [start] => 24 [label] => 7 ) [7] => stdClass Object ( [start] => 28 [label] => 8 ) ) [estimatedResultCount] => 258000000 [currentPageIndex] => 0 [moreResultsUrl] => http://www.google.com/search?oe=utf8&ie=utf8&source=uds&start=0&hl=en&q=test [searchResultTime] => 0.32 ) ) [responseDetails] => [responseStatus] => 200 )
I want to access a property of an object but this is not working:
$jsonNew = $json->{'results'};
print_r($jsonNew);
And by the way it doesn't throw an error or warning. It just displays nothing. Any ideas?
I googled it but I can't find any further information about the Google Search API and how to use the result of search query.

You can access the required element as $json->responseData->results[$x]. where $x is the element number.
Or you could also simply loop through the entire thing as
for($x=0;$x<count($json->responseData->results);$x++){
echo "</br>URL: ";
echo $json->responseData->results[$x]->url;
echo "</br>VisibleURL: ";
echo $json->responseData->results[$x]->visibleUrl;
echo "</br>Title: ";
echo $json->responseData->results[$x]->title;
echo "</br>Content: ";
echo $json->responseData->results[$x]->content;
echo "</br>";
}

Related

PHP stdClass Object - foreach

I'm using an API to get domain DNS details. The results printed show like this:
stdClass Object
(
[test.co.uk] => stdClass Object
(
[records] => Array
(
[0] => stdClass Object
(
[mname] => ns1.test.com.
[rname] => hostmaster.test.com.
[serial] => 12345678
[refresh] => 1800
[retry] => 900
[expire] => 1209600
[minimum-ttl] => 300
[ref] =>
[host] => test.co.uk
[type] => SOA
)
[1] => stdClass Object
(
[target] => ns1.test.com
[ref] =>
[host] => test.co.uk
[type] => NS
)
[2] => stdClass Object
(
[target] => ns2.test.com
[ref] =>
[host] => test.co.uk
[type] => NS
)
How can I turn each of the records ([0], [1], [2] etc) into variables? I am wanting to show them in a table
I have tried the below, but no result is shown
$Test=$PackageDNSInfo->test.co.uk->records[0]->mname;
echo $Test;
Just use foreach on it, just like you would on an array:
foreach ($PackageDNSInfo as $url => $data) {
foreach ($data->records as $record) {
$type = $record->type;
$host = $record->host;
// etc.
}
}
If you want to access a given URL's data directly, use curly braces:
echo $PackageDNSInfo->{'test.co.uk'}->records[0]->mname;

decode json response to get json parameter value

Here is my json response:
stdClass Object ( [is_claimed] => [rating] => 4 [mobile_url] => http://m.yelp.com/biz/the-waterboy-sacramento [rating_img_url] => http://s3-media4.ak.yelpcdn.com/assets/2/www/img/c2f3dd9799a5/ico/stars/v1/stars_4.png [review_count] => 455 [name] => The Waterboy [snippet_image_url] => http://s3-media1.ak.yelpcdn.com/photo/SZyFYvQmHWSLhK96SSzwwA/ms.jpg [rating_img_url_small] => http://s3-media4.ak.yelpcdn.com/assets/2/www/img/f62a5be2f902/ico/stars/v1/stars_small_4.png [url] => http://www.yelp.com/biz/the-waterboy-sacramento [menu_date_updated] => 1387494198 [reviews] => Array ( [0] => stdClass Object ( [rating] => 5 [excerpt] => AMAZING again, went here last Thursday at 5:00pm. Greeted by friendly man, he asked if we had a reservation, I said, 'no, do we need one?' He said, I'm... [time_created] => 1395158338 [rating_image_url] => http://s3-media1.ak.yelpcdn.com/assets/2/www/img/f1def11e4e79/ico/stars/v1/stars_5.png [rating_image_small_url] => http://s3-media1.ak.yelpcdn.com/assets/2/www/img/c7623205d5cd/ico/stars/v1/stars_small_5.png [user] => stdClass Object ( [image_url] => http://s3-media1.ak.yelpcdn.com/photo/SZyFYvQmHWSLhK96SSzwwA/ms.jpg [id] => H0qUqWctz5Ms6qdeaIvjFw [name] => Lori T. ) [rating_image_large_url] => http://s3-media3.ak.yelpcdn.com/assets/2/www/img/22affc4e6c38/ico/stars/v1/stars_large_5.png [id] => bZznirkpADmW3Qcpc5u_VA ) ) [phone] => 9164989891 [snippet_text] => AMAZING again, went here last Thursday at 5:00pm. Greeted by friendly man, he asked if we had a reservation, I said, 'no, do we need one?' He said, I'm... [image_url] => http://s3-media1.ak.yelpcdn.com/bphoto/9e5sodvvP3p6_53wOqVTcg/ms.jpg [categories] => Array ( [0] => Array ( [0] => French [1] => french ) [1] => Array ( [0] => Italian [1] => italian ) ) [display_phone] => +1-916-498-9891 [rating_img_url_large] => http://s3-media2.ak.yelpcdn.com/assets/2/www/img/ccf2b76faa2c/ico/stars/v1/stars_large_4.png [menu_provider] => single_platform [id] => the-waterboy-sacramento [is_closed] => [location] => stdClass Object ( [city] => Sacramento [display_address] => Array ( [0] => 2000 Capitol Ave [1] => Midtown [2] => Sacramento, CA 95811 ) [neighborhoods] => Array ( [0] => Midtown ) [postal_code] => 95811 [country_code] => US [address] => Array ( [0] => 2000 Capitol Ave ) [state_code] => CA ) )
which I get using:
$response = json_decode($data);
print_r($response);
echo $response["rating"]; //Why this does not give json response value?
Pass true into the second parameter of json_decode to return an array (which is how you're trying to access it):
$response = json_decode($data, true); // associative array returned
print_r($response);
echo $response["rating"]; // 4
Manual
Otherwise, access the rating as a property of the object that you've got:
$response = json_decode($data);
echo $response->rating; // 4

Get image url via xml in php

php code:
<?php
$url = 'https://www.rudolphs-christmasshop.com.au/api/v2/products/';
$username ='xyz'; $password ='ca25fe6947564b9479sdfsaffsaffasfasfsaffdasfe5866b4';
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERPWD,$username . ':' . $password);
$result = curl_exec($ch); curl_close($ch);
$xml = simplexml_load_string($result);
?>
output
SimpleXMLElement Object (
[product] => Array (
[0] => SimpleXMLElement Object (
[id] => 29
[name] => SimpleXMLElement Object ( )
[type] => physical
[sku] => 22254
[description] => SimpleXMLElement Object ( )
[search_keywords] => SimpleXMLElement Object ( )
[availability_description] => SimpleXMLElement Object ( )
[price] => 22.9500
[inventory_warning_level] => 5
[warranty] => SimpleXMLElement Object ( )
[weight] => 0.2500
[width] => 13.0000
[height] => 11.0000
[depth] => 8.0000
[view_count] => 125
[page_title] => Aussie Koala and Baby Christmas Ornament - Australiana
[meta_keywords] => koala bear decoration, koala christmas ornament, australian decorations, aussie christmas, christmas decoration
[meta_description] => SimpleXMLElement Object ( )
[layout_file] => product.html
[is_price_hidden] => false
[price_hidden_label] => SimpleXMLElement Object ( )
[categories] => SimpleXMLElement Object (
[value] => 30
)
[downloads] => SimpleXMLElement Object (
[link] => /products/29/downloads )
[images] => SimpleXMLElement Object (
[link] => /products/29/images
)
)
)
)
)
How could I get the image url and display image on browser
May be wrong but I guess like this if I look here
echo $xml->product[0]->downloads->images->link;
But if you show us your XML we are more able to help you.
Greets
I can't test it here. But you can access the tree with:
if you have more products:
<?php
foreach($xml->product as $pout ) {
echo $pout->downloads->images->link;
}
?>
if you want only one product something like this:
$xml->product[0]->downloads->images->link;

How to loop through this array and print one result in each line using php

How can I loop through this array and print one result in each line. This is returned by google search api.
This works for me
print_r($rez->responseData);
But this doesn't
print_r($rez->responseData->results); nor this print_r($rez->responseData['results']);
Below is the array
stdClass Object
(
[results] => Array
(
[0] => stdClass Object
(
[GsearchResultClass] => GwebSearch
[unescapedUrl] => http://www.1860-1960.com/shoes.html
[url] => http://www.1860-1960.com/shoes.html
[visibleUrl] => www.1860-1960.com
[cacheUrl] => http://www.google.com/search?q=cache:4bB2OicXg5EJ:www.1860-1960.com
[title] => Beautiful <b>Antique Shoes</b> and Boots, Vintage Fashions
[titleNoFormatting] => Beautiful Antique Shoes and Boots, Vintage Fashions
[content] => <b>Vintage</b> Clothing. <b>Shoes</b> & boots Hats & bonnets. Parasols, purses, fans & more. Textiles & trims. New Items. ebay auctions. Find out how to order About us Click <b>...</b>
)
[1] => stdClass Object
(
[GsearchResultClass] => GwebSearch
[unescapedUrl] => http://www.ebay.com/sch/Pre1920-Edwardian-Older-/74977/i.html?_nkw=antique+shoes
[url] => http://www.ebay.com/sch/Pre1920-Edwardian-Older-/74977/i.html%3F_nkw%3Dantique%2Bshoes
[visibleUrl] => www.ebay.com
[cacheUrl] => http://www.google.com/search?q=cache:gKFzby7zoS0J:www.ebay.com
[title] => <b>antique shoes</b> | eBay
[titleNoFormatting] => antique shoes | eBay
[content] => eBay: <b>antique shoes</b>. <b>...</b> Quick Look. Antique 1905 Silk Satin Bridal Wedding Shoes Pumps Louis XV Heels Beautiful. Buy It Now $31.90 <b>...</b>
)
[2] => stdClass Object
(
[GsearchResultClass] => GwebSearch
[unescapedUrl] => http://www.amazon.com/Winsome-Wood-Shoe-Antique-Walnut/dp/B000NPQKHO
[url] => http://www.amazon.com/Winsome-Wood-Shoe-Antique-Walnut/dp/B000NPQKHO
[visibleUrl] => www.amazon.com
[cacheUrl] => http://www.google.com/search?q=cache:SBPbbjdSIpMJ:www.amazon.com
[title] => Amazon.com: Winsome Wood <b>Shoe</b> Rack, <b>Antique</b> Walnut: Home <b>...</b>
[titleNoFormatting] => Amazon.com: Winsome Wood Shoe Rack, Antique Walnut: Home ...
[content] => <b>Shoe</b> Rack. With Removable Sink tray, this unique product is nice to have it especially in wet weather.Warm Walnut finish <b>...</b>
)
[3] => stdClass Object
(
[GsearchResultClass] => GwebSearch
[unescapedUrl] => http://trouvais.com/category/antique-shoes/
[url] => http://trouvais.com/category/antique-shoes/
[visibleUrl] => trouvais.com
[cacheUrl] => http://www.google.com/search?q=cache:qPcTFS0bBR4J:trouvais.com
[title] => <b>Antique shoes</b> « Trouvais
[titleNoFormatting] => Antique shoes « Trouvais
[content] => 19th century silk <b>shoes</b>, and then stumbled upon. this tattered silk pair inscribed with a wedding date c1773. <b>antique</b> textiles. I'm happy with just a few tangible <b>...</b>
)
)
[cursor] => stdClass Object
(
[resultCount] => 11,400,000
[pages] => Array
(
[0] => stdClass Object
(
[start] => 0
[label] => 1
)
[1] => stdClass Object
(
[start] => 4
[label] => 2
)
[2] => stdClass Object
(
[start] => 8
[label] => 3
)
[3] => stdClass Object
(
[start] => 12
[label] => 4
)
[4] => stdClass Object
(
[start] => 16
[label] => 5
)
[5] => stdClass Object
(
[start] => 20
[label] => 6
)
[6] => stdClass Object
(
[start] => 24
[label] => 7
)
[7] => stdClass Object
(
[start] => 28
[label] => 8
)
)
[estimatedResultCount] => 11400000
[currentPageIndex] => 0
[moreResultsUrl] => http://www.google.com/search?oe=utf8&ie=utf8&source=uds&start=0&hl=en&q=antique+shoes
[searchResultTime] => 0.14
)
)
This is the code that generates this.
<?php
/**
* google_search_api()
* Query Google AJAX Search API
*
* #param array $args URL arguments. For most endpoints only "q" (query) is required.
* #param string $referer Referer to use in the HTTP header (must be valid).
* #param string $endpoint API endpoint. Defaults to 'web' (web search).
* #return object or NULL on failure
*/
function google_search_api($args, $referer = 'http://localhost/test/', $endpoint = 'web'){
$url = "http://ajax.googleapis.com/ajax/services/search/".$endpoint;
if ( !array_key_exists('v', $args) )
$args['v'] = '1.0';
$url .= '?'.http_build_query($args, '', '&');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// note that the referer *must* be set
curl_setopt($ch, CURLOPT_REFERER, $referer);
$body = curl_exec($ch);
curl_close($ch);
//decode and return the response
return json_decode($body);
}
print_r($rez->responseData);
Something like:
$obj = new obj(); // your object
function printLies($obj)
{
foreach ($obj as $elem)
{
if (is_array($elem) || is_object($elem))
{
printLies($obj);
}
else
{
echo $elem . '<br />';
}
}
}
Or I didn't understand the question? Maybe you meant this?
$obj = new obj(); // your object
foreach ($obj->result as $result)
{
print_r($result);
}

store SimpleXMLElement Object value and images in database

I'm trying to read a rss feed and store its value in my database . for this I'm using this
$homepage = file_get_contents('http://showmycode.co.in/supermob/feeds/rss/Jaipur');
$movies = new SimpleXMLElement($homepage);
echo '<pre>';
print_r($movies);
and then I found
SimpleXMLElement Object
(
[#attributes] => Array
(
[version] => 2.00
)
[channel] => SimpleXMLElement Object
(
[title] => supermobdeal
[description] => best discount accross canada
[link] => SimpleXMLElement Object
(
)
[lastBuildDate] => Thu, Nov 3rd 2011, 00:32 GMT
[generator] => supermobdeal
[image] => SimpleXMLElement Object
(
[url] => http://showmycode.co.in/supermob/app/webroot/img/site_logo.png
[title] => supermobdeal
[link] => http://showmycode.co.in/supermob/app/webroot/img/site_logo.png
[description] => Feed provided by supermobdeal
)
[item] => Array
(
[0] => SimpleXMLElement Object
(
[title] => Let your
[link] => http://showmycode.co.in/supermob/homes/index/Jaipur/25
[small_image_url] => http://showmycode.co.in/supermob/app/webroot/img/uploads/product_images/small/
[description] => trainers r any course
[start_date] => 2011-10-26
[end_date] => 2011-11-30
[start_time] => 09:26:00
[end_time] => 09:26:50
[price] => 50$
[value] => 199$
[discount] => 74.87%
[city] => Jaipur
)
[1] => SimpleXMLElement Object
(
[title] => Feel a
[link] => http://showmycode.co.in/supermob/homes/index/Jaipur/31
[small_image_url] => http://showmycode.co.in/supermob/app/webroot/img/uploads/product_images/small/3b8d0_Jaip_OrientSpa_24thOct_M_1.jpg
[description] => Orient Spa
[city] => Jaipur
)
[2] => SimpleXMLElement Object
(
[title] => Feel a
[link] => http://showmycode.co.in/supermob/homes/index/Jaipur/26
[small_image_url] => http://showmycode.co.in/supermob/app/webroot/img/uploads/product_images/small/0a646_Bombay-Biryani1.jpg
[description] => Taxes
[city] => Jaipur
)
)
)
)
how can I store tittle , link or other attributes in my database and store image in folder
//get contanints from SimpleXMLElement Object
foreach($movies->channel->item as $opt){
$title= $opt->title;
$tittle=mysql_real_escape_string($title); //for Escapes special characters in a string you can use for all varriables if require
$link=$opt->link;
$des=$opt->description;
$image=$opt->medium_image_url;
//for store image from http url to my folder
$ch = curl_init($image);
$fp = fopen('images/'. time () .'.'.'jpg', 'wb');//path for store image
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);
include('db.php');//config file for db connection
$sql="INSERT INTO rss (tittle, link, image,description,city)
VALUES ('$tittle', '$link', '$image','$des','$city')";//insert record in database table
$result=mysql_query($sql) or die('Error, insert query failed');
this code store varriables value in your database and image in folder from http url.thanks..

Categories