JSON PHP parsing search API - php

Alright, I'm using the Blekko search API:
http://blekko.com/ws/?q=hello+%2Fjson
how would I go about parsing it ?
I have no experience of parsing JSON from PHP, so I'd appreciate a little help, and the json_decode() docs failed to explain everything for me, particularly getting the data inside RESULT. :) You know, [ and ].
Could you help pointing me in the right direction ? :)
Thank you, you're all so helpful! :)

Here's the code to access the API.
You should enter your own error/unexpected results handling where i've left the comments.
$data = file_get_contents('http://blekko.com/ws/?q=hello+%2Fjson');
if(!empty($data)){
$data = json_decode($data);
if(!empty($data->ERROR)){
// Error with API response.
} else {
$data = $data->RESULT;
if(empty($data)){
// No results.
} else {
// Uncomment the line below to see your data
// echo '<pre>' . print_r($data) . '</pre>';
foreach($data AS $key => $val){
echo $val->short_host . '<br />';
}
}
}
} else {
// Failed to retrieve data.
}

Related

php file_get_contents() returning false with a valid url

I'm currently working on a geocoding php function, using google maps API. Strangely, file_get_contents() returns bool(false) whereas the url I use is properly encoded, I think.
In my browser, when I test the code, the page takes a very long time to load, and the geocoding doesn't work (of course, given that the API doesn't give me what I want).
Also I tried to use curl, no success so far.
If anyone could help me, that'd be great !
Thanks a lot.
The code :
function test_geocoding2(){
$addr = "14 Boulevard Vauban, 26000 Valence";
if(!gc_geocode($addr)){
echo "false <br/>";
}
}
function gc_geocode($address){
$address = urlencode($address);
$url = "http://maps.google.com/maps/api/geocode/json?address={$address}";
$resp_json = file_get_contents($url);
$resp = json_decode($resp_json, true);
if($resp['status']=='OK'){
$lati = $resp['results'][0]['geometry']['location']['lat'];
$longi = $resp['results'][0]['geometry']['location']['lng'];
if($lati && $longi){
echo "(" . $lati . ", " . $longi . ")";
}else{
echo "data not complete <br/>";
return false;
}
}else{
echo "status not ok <br/>";
return false;
}
}
UPDATE : The problem was indeed the fact that I was behind a proxy. I tested with another network, and it works properly.
However, your answers about what I return and how I test the success are very nice as well, and will help me to improve the code.
Thanks a lot !
The problem was the fact that I was using a proxy. The code is correct.
To check if there is a proxy between you and the Internet, you must know the infrastructure of your network. If you work from a school or a company network, it is very likely that a proxy is used in order to protect the local network.
If you do not know the answer, ask your network administrator.
If there is no declared proxy in your network, it is still possible that a transparent proxy is there. However, as states the accepted answer to this question: https://superuser.com/questions/505772/how-can-i-find-out-if-there-is-a-proxy-between-myself-and-the-internet-if-there
If it's a transparent proxy, you won't be able to detect it on the client PC.
Some website also provide some proxy detectors, though I have no idea of how relevant is the information given there. Here are two examples :
http://amibehindaproxy.com/
http://www.proxyserverprivacy.com/free-proxy-detector.shtml
When you are not return anything function returns null.
Just use that:
if(!is_null(gc_geocode($addr))) {
echo "false <br/>";
}
Or:
if(gc_geocode($addr) === false) {
echo "false <br/>";
}
Take a look at the if statement:
if(!gc_geocode($addr)){
echo "false <br/>";
}
This means that if gc_geocode($addr) returns either false or null, this statement will echo "false".
However, you never actually return anything from the function, so on success, it's returning null:
$address = urlencode($address);
$url = "http://maps.google.com/maps/api/geocode/json?address={$address}";
$resp_json = file_get_contents($url);
$resp = json_decode($resp_json, true);
if($lati && $longi){
echo "(" . $lati . ", " . $longi . ")"; //ECHO isn't RETURN
/* You should return something here, e.g. return true */
} else {
echo "data not complete <br/>";
return false;
}
} else {
echo "status not ok <br/>";
return false;
}
Alternatively, you can just change the if statement to only fire when the function returns false:
if(gc_geocode($addr)===false){
//...
Above function gc_geocode() working properly on my system, without any extra load. You have called gc_geocode () it returns you lat, long that is correct now you have check through
if(!gc_geocode($addr)){
echo "false <br/>";
}
Use
if($responce=gc_geocode($addr)){
echo $responce;
}
else{
echo "false <br/>";
}

My PHP function won't return the response to AJAX until the process finishes

I need the PHP response as it is outputted on the php echo.
But when I have a process running, it returns all at once, only after the process has ended.
Is there a way around this?
Thank you in advance
Edit:
This is the ajax after getting the response:
// callback handler called on success
request.done(function (response) {
$('#add--response').html(response);
});
This is the PHP
$count=0;
foreach ($_POST['URLS'] as $url) {
if(!empty($url)){
echo '<div id="conversionSuccess">here is the progress bar for the download</div>';
if (<here I download a file that takes a long time>)
{
echo "success";
}
else
{
echo 'Error!';
}
$count++;
echo "count: ".$count."<br>";
}
}
I want the progress bar visible before the file finishes downloading.
I hope now it makes sense
Without your code, its hard to understand what you're asking or how to help. For better practice, please attach code in your next questions.
However, I'd approach this by building the string in a way you can then later split it and use the response: this meaning -
$response = "";
$response .= $outputOne . "/";
$response .= $outputTwo . "/";
echo $reponse;
Inside your JQuery:
var output = reponse.split("/");
output now becomes an array of each of your output's.
Hope this was relevant and helped.

How to use Post to URL feature of plugin

I'm wondering if anyone could help me out in trying to use a feature of my form plugin (FormCraft for Wordpress) that allows the form data to be sent to a URL. There's no documentation on this feature and I can't figure it out. Here's a screenshot of the options:
I've created an empty form_data.php file and uploaded it to my site, then put that URL in the field seen in the screenshot. Nothing happens in the php file when I submit a form. The support team for the plugin hasn't been very helpful, they just said, "You need to make sure the script on that URL will catch and parse the data." Is there anything that I would need to add to the php file to get this to work?
Send the data to this file below.
http://localhost/bellow_file.php
<?php
$json = json_encode($_REQUEST, JSON_UNESCAPED_UNICODE);
$json = json_decode($json,true);
$data = "";
foreach ($json as $key => $val) {
if(is_array($val)) {
$data .= "$key:\n";
} else {
$data .= "$key => $val\n";
}
}
file_put_contents('test.txt', $data);
?>

Check if Youtube video valid? Code Fix

ive a database with around 5000 videos and i noticed some of them are removed now.. SO i decided to write a php script to fix bulk check this..
From the various sources below is the code i implemented based on most answers here, but it doesnt give correct results. IT gives a 403 header for 3/4th videos though practically more than 90% are working..Am i missing anything?
foreach ($video as $cat) {
$str = explode("=",$cat->videourl);
$headers = get_headers('http://gdata.youtube.com/feeds/api/videos/' . $str[1]);
if (!strpos($headers[0], '200')) {
print_r($headers[0].'<br>');
$i=$i+1;
print_r("Unpublish".$cat->id. PHP_EOL);
}
else{
print_r("publish".$cat->id. PHP_EOL);
}
}
I'm printing the header here to debug it, and for most it gives, HTTP/1.0 403 Forbidden
Edit :: ive already checked the videoids are passed correctly(so string processing has no issues)
For anyone trying to achieve this, here is the code.. do appreciate if works for you as ive spend hours to get it working for the new api
$headers = checkYoutubeId ($str[1]);
if ($headers == false) {
$i=$i+1;
$db->query('UPDATE `ckf_hdflv_upload` SET `published`="0" Where `id`='.$cat->id);
print_r("Unpublished".$cat->id. PHP_EOL);
}
else{
$db->query('UPDATE `ckf_hdflv_upload` SET `published`="1" Where `id`='.$cat->id);
}
}
}
echo('done'.$i);
function checkYoutubeId($id) {
if (!$data = #file_get_contents("http://gdata.youtube.com/feeds/api/videos/".$id)) return false;
if ($data == "Video not found") return false;
if ($data == "Private video") return false;
return true;
}

Issue with my PHP Webservice not giving valid JSON

I'm using the Class "mysql2json" to make my Json.
<?php
class mysql2json{
static public function getJSON($resultSet,$affectedRecords){
mb_internal_encoding("UTF-8");
$numberRows=0;
$arrfieldName=array();
$i=0;
$json="";
//print("Test");
while ($i < mysql_num_fields($resultSet)) {
$meta = mysql_fetch_field($resultSet, $i);
if (!$meta) {
}else{
$arrfieldName[$i]=$meta->name;
}
$i++;
}
$i=0;
$json="{\n\"data\": [\n";
while($row=mysql_fetch_array($resultSet, MYSQL_NUM)) {
$i++;
//print("Ind ".$i."-$affectedRecords<br>");
$json.="{\n";
for($r=0;$r < count($arrfieldName);$r++) {
$json.="\"$arrfieldName[$r]\" : \"$row[$r]\"";
if($r < count($arrfieldName)-1){
$json.=",\n";
}else{
$json.="\n";
}
}
if($i!=$affectedRecords){
$json.="\n},\n";
}else{
$json.="\n}\n";
}
}
$json.="]\n};";
return $json;
}
}
?>
The problem is I'm getting a not valid JSON error in Xcode (iPhone App) and the JSON validator is saying there is an error on line 11 of the results even though line 11 is blank.
Validator: http://jsonlint.com/
Here is a sample URL.
http://leafseed.com/webservice.php?upc=1116102338
Xcode Error:
2012-01-11 08:55:46.137 GroceryVine[6476:bf03] -JSONValue failed. Error trace is: (
"Error Domain=org.brautaset.JSON.ErrorDomain Code=10 \"Garbage after JSON\" UserInfo=0x9bbabc0 {NSLocalizedDescription=Garbage after JSON}
Validator Error
Parse error on line 11:
...." } ]};
--------------------^
Expecting 'EOF', '}', ',', ']'
Any Ideas?
Best Solution
I wouldn't bother with this class. Just use the native json_encode() DOCs PHP function as it will give you correctly formatted JSON very easily every time.
For example:
$json_arr = array();
while($row = mysql_fetch_array($resultSet, MYSQL_NUM)) {
$json_arr[] = $row;
}
echo json_encode($json_arr);
A list of other PHP JSON implementations can be found on the json.org website (hint: scroll down).
Direct answer
Looking at your updated question with debug output. Looks like there is an errant semi-colon (;) in your output.
Change your last append from
$json.="]\n};";
to
$json.="]\n}";
And I think that will fix your issue.
what about json_encode function and fetch data separately ?
http://php.net/manual/en/function.json-encode.php
The ; after the last curly brace is wrong
Replacing:
}
$json.="]\n};";
return $json;
}
With
}
$json.="]\n}";
return $json;
}
should solve your problem.

Categories