Parse Google Images API Json PHP - php

Hey, well I'm trying to use google images api with PHP, and I'm really not sure what to do.
This is basically what I have right now:
$jsonurl = "https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=test";
$json = file_get_contents($jsonurl,0,null,null);
$json_output = json_decode($json);
Where would I go from there to retrieve the first image url?

With a minor change to the last line of your code sample, the following will output the url of the first image in the result set.
<?php
$jsrc = "https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=test";
$json = file_get_contents($jsrc);
$jset = json_decode($json, true);
echo $jset["responseData"]["results"][0]["url"];
?>

For security reasons, most server configurations won't let you use file_get_contents on a remote file (different domain name). It would potentially allow a hacker to load code from anywhere on the Internet to your site, then execute it.
Even if your server configuration does allow for it, then I wouldn't recommend using it for this purpose. The standard tool for retrieving remote HTTP data is cURL, and there are plenty of good tutorials out there doing exactly what you should do in this case.
So, let's say you've successfully used cURL to retrieve the JSON array.
$json_output = json_decode($json); // Now the JSON is an associative array
foreach ($json_output['responseData']['results'] as $result)
{
echo $result['url'] . '<br />';
}
Of course, you don't have to echo the URL there; you can do whatever you need to with the value.

I have to say, this is 10 shades of awesome.. But I come with bad news (don't shoot the messenger..)
Important: The Google Image Search API has been officially deprecated as of May 26, 2011. It will continue to work as per our deprecation policy, but the number of requests you may make per day may be limited.
That is, as they same, lame.
I feel as if Google might have hired one-too-many layed-off-from-IBM-types... as they seem to be killing off all their "cool" API's.
They launch services haphazardly, promising this and that and the other thing... but then some middle-manager gets screamed at after realizing (ta-da!) that XYZ project doesn't generate income (like image results without ads, lol) and then... they axe it..
Lesson: Don't get married (aka build your software or service) around any google API you can't replace on-the-fly at a moment's notice... Now, I'm no LTS-junkie - I'm just bitter because I'd much rather get my Google results via XML or JSON than the icky HTML-soup they throw at you...
One Question #Marcel... How can I get an array, or at least multiple JSON result responses using that same "formula". I thought maybe the 1 meant "result 1", but alas, no... Is their a "trick" to generate a content stream ala a Picasa xml feed?

Related

How to display Now Playing in my website with Icecast2 and Liquidsoap

I couldn't find any better answer to this online, even the document of liquidsoap isn't helpful. What I want to happen is to grab the current song title and artist being played in my streaming server(icecast). I found in some forum that they were able to do it but they didn't explain it how, here's the liquidsoap script that they used:
def apply_metadata(m) =
title = m["title"]
artist = m["artist"]
album = m["album"]
[("artist","#{artist}"),("title","#{album} - #{title}")]
end
centovacast.callback_autodj := fun(s) -> map_metadata(apply_metadata,s)
This script i believe is also for centova and autodj only. While I do not use those technology (I'm using Ubuntu 16.04, Icecast2, Liquisoap, PHP, HTML5/CSS),
is this possible to do using the tools I'm currently using?
I used to use websockets to get the metadata but I found it frustrating that it was always out of sync.
The only way to solve it is to have the metadata encoded into the stream so you receive it at the same time as the audio.
I did a bit of digging around to find out how the icecast servers do it and put together a service worker script which adds the necessary header to your request to obtain a stream including metadata and then extracts it for you.
The code is here and there is a simple demo here
I hope this helps, anyway, I think that here, weserWEB, has already somehow said something similar.
If you're using Icecast version 2.4.4 you can consume the metadata from this endpoint: (if not, consider downloading that version)
http://<your-ipaddress-or-domain>:<port_number>/status-json.xsl
Just put that in any browser and you will get a JSON with the name of the song and title you are streaming, you have to configure properly your streaming client first, of course.
Then you can get the metadata from that endpoint without problems in your PHP. You can use CURL to get the JSON data, liquidsoap not necessary.
I'm not sure why you are dragging the source client into this.
A proper stream sent to an Icecast mountpoint will have metadata for currently playing audio.
This has been pointed out elsewhere. Icecast since 2.4.1 provides a proper JSON metadata export.
Querying JSON from within a website is very much a solved problem and considered an exercise for the inclined reader.
Why don't you grab this at icecast directly?
PHP:
function get_icecast_info($server_ip, $server_port, $admin_user, $admin_password) {
$index = #file_get_contents("http://".$admin_user.":".$admin_password."#".$server_ip.":".$server_port."/admin/stats.xml");
if($index) {
$xml = new DOMDocument(); if(!$xml->loadXML($index)) return false; $arr = array(); $listItem = $xml->getElementsByTagName("source");
foreach($listItem as $element) {
if($element->childNodes->length) {
foreach($element->childNodes as $i){ $arr[$element->getAttribute("mount")][$i->nodeName] = $i->nodeValue; }
}
}
return $arr;
} return false;
}
And this is the output (array):
$arr = get_icecast_info($ice_host, $ice_aport, $ice_user, $ice_pass);

splitting apart response from an API

I am trying to start using APIs, doing calls and so forth. Just barely starting to learn. Found a way to get Facebook shares on a post using the graph api.
I did this with PHP; here is the code:
$response = file_get_contents('https://graph.facebook.com/? id=mydomain.com');
echo $response;
this is the response that I get:
{"id":"http://sportsmockery.com/2014/11/hey-bears-fire-everyone/","shares":22}
What I want is to somehow get the share count (22) into a variable so I can do stuff with it…(i changed the domain that gets that share count to my domain.com);
anyway; I am not sure what is the standard way to do this, if you control what is received with how you do your call; or if you just get the full response and pull out what you want…
Been looking around and have not been able to find anything that will really help with this.
I am hoping someone can help me with this…
All the best, G
Use json_decode() which will make all of the properties easily accessible.
$parsedResponse = json_decode($response);
$count = $parsedResponse->shares;
echo $count;
This is a json response.
Parsing JSON file with PHP
http://php.net/manual/en/function.json-decode.php

I want to send requests from a UE4 c++ game to my php script, so that it interacts with a mysql database

i'm searching the inet for around 3 days now and i'm stuck at this.
I got a MySQL Database and a php Script, as well as a Game made in UE4.
UE4 uses c++.
So now i want to send requests from the c++ game to the php script and that shall interact with the database.
For example create an account or login. I also want to pass the mysql query result of the php script to my c++ class.
I tried using HttpRequest, but i can't get data from php to c++ with that.
Maybe you can, but i don't understand it at all.
What i accomplished by now is that you can send a POST request from the game to the php script and pass variables so that the script uses them to perform the mysql query.
But how can i pass data from the php file to c++ now? The response i get is always the whole site (head and body) and i don't know where i could save the query result to pass it to the c++ code.
I'm a full beginner here, so go easy on me. I read so many different posts and blogs that my brain hurts like hell ): I hope someone can tell me how to do this easily or at least give me a hint on what i have to google and what i could use. I don't need a full tutorial, just a name of a library better than the Http.h (if simple HttpRequest cant manage this) would be enough. ): I'm really frustrated...
eXi
The PHP script should retun a HTTP response reduced to a bare minimum. It doesn't even need to be a HTML document:
<?php
// file: api.php
$param = $_POST['myparam'];
$foo = bar($param); // $foo contains e.g. "1,ab,C"
echo $foo; // if you opened http://myhost.com/api.php in a browser
// all you would see is "1,ab,C"
// (which is not a valid HTML document, but who cares)
?>
Then parse this HTTP response (a plain string, that is) from your game. You can use your own data format, or use a well-known format of your choice (XML or JSON are good candidates).
The json object in unreal is pretty good, so I would recommend outputting json from your php script. Json in php is a pretty natural workflow.
<?php
$obj['userid'] = 5476;
$obj['foo'] = 'bar';
echo json_encode($obj);
php?>
That will echo out
{"userid":5476,"foo":"bar"}
If that's all you output in your script then it's pretty straightforward to treat that as a string and populate an unreal json object with it.
FString TheStuffIGotFromTheServer;
TSharedPtr<FJsonObject> ParsedJson;
TSharedRef<TJsonReader<TCHAR>> JsonReader = TJsonReaderFactory<TCHAR>::Create(TheStuffIGotFromTheServer);
if (FJsonSerializer::Deserialize(JsonReader, ParsedJson))
{
FString foo = ParsedJson.GetStringField("foo");
double UserId = ParsedJson.GetNumberField("userid");
}
Check out the unreal json docs to get a feel for what you can do with it.

HTML content extraction using Diffbot

Can someone help me I want to extract html data from http://www.quranexplorer.com/Hadith/English/Index.html. I have found a service that does exactly that http://diffbot.com/dev/docs/ they support data extraction via a simple api, the problem it that I have a large number of url that needs that needs to be processed. The link below http://test.deen-ul-islam.org/html/h.js
I need to create a script that that follows the url then using the api generate the json format of the html data (the apis from the site allows batch requests check website docs)
Please note diffbot only allows 10000 free request per month so I need a way to save the progress and be able to pick up where I left off.
Here is an example I created using php.
$token = "dfoidjhku";// example token
$url = "http://www.quranexplorer.com/Hadith/English/Hadith/bukhari/001.001.006.html";
$geturl="http://www.diffbot.com/api/article?tags=1&token=".$token."&url=".$url;
$json = file_get_contents($geturl);
$data = json_decode($json, TRUE);
echo $article_title=$data['title'];
echo $article_author=$data['author'];
echo $article_date=$data['date'];
echo nl2br($article_text=$data['text']);
$article_tags=$data['tags'];
foreach($article_tags as $result) {
echo $result, '<br>';
}
I don't mind if the tool is in javascript or php I just need a way to get the html data in json format.
John from Diffbot here. Note: not a developer, but know enough to write hacky code to do simple things.
You have a list of links -- it should be straightforward to iterate through those, making a call to us for each.
Here's a Python script that does such: https://gist.github.com/johndavi/5545375
I used a quick search regex in Sublime Text to pull out the links from the JS file.
To truncate this, just cut out some of the links, then run it. It will take a while as I'm not using the Batch API.
If you need to improve or change this, best seek out a stronger developer directly. Diffbot is a dev-friendly tool.

How do I use external JSON...?

spent a few hours trying to figure this out, but cannot for the life of me figure out what's going wrong.
All I'm trying to do is load this:
https://recruit.zoho.com/ats/EmbedResult.hr?jodigest=2cV.Sr2As6VxhLMxQGuTNij*g.Fb3J7ysduDs.AC9sU-&atslocale=en_GB&rawdata=json
which I believe is json, into either javascript/jquery or php and use the data.
I've looked into jsonp, followed some tutorials, used some demos as templates and just can't get the above data to work.
If anyone can shed some light it would be much appreciated. It really shouldn't be this complicated, but I don't know what's going wrong.
Yep, that's JSON. The site may not support JSONP, so you're gonna have to use PHP to do this.
This is untested, but should work.
<?php
$url = 'https://recruit.zoho.com/ats/EmbedResult.hr?jodigest=2cV.Sr2As6VxhLMxQGuTNij*g.Fb3J7ysduDs.AC9sU-&atslocale=en_GB&rawdata=json';
$JSON = file_get_contents($url);
// echo the JSON (you can echo this to JavaScript to use it there)
echo $JSON;
// You can decode it to process it in PHP
$data = json_decode($JSON);
var_dump($data);
?>
JSONP relies on the server to return a JSONP formatted response. Basically, to use JSONP the server needs to return a JSON string wrapped in a function invocation ({"foo":1} becomes func({"foo":1})).
As the server your using doesn't return a JSONP response, you cannot use JSONP, you can only use JSON.
This is a shame, as JSON cannot be used x-domain due to the same origin policy (SOP). Therefore, the only option you have is to use a proxy server, which retrieves the JSON from the server, and either gives it to you in JSONP (see Yahoo Pipes), or which is on the same domain as the requested page (write a simple PHP script to get the file using file_get_contents() and then echo the output), in which case it can return the JSON.
I breifly looked at the requirements and it looks like you need an API key as well as an account. I saw that the site provides services for XML and JSON only. It looks to be fairly well documented.

Categories