Parse JSON Freebase results in PHP - php

I'm really sorry if this is too basic, but I really don't know how to do this.
I'm using this jquery Autocomplete plugin: http://devthought.com/wp-content/projects/jquery/textboxlist/Demo/
EDIT: This is the jquery code i use for the autocomplete:
$(function() {
var t = new $.TextboxList('#form_topick_tags', {unique: true, plugins: {autocomplete: {
minLength: 2,
queryRemote: true,
remote: {url: 'autocomplete2.php'}
}}});
The plugin uses a PHP for autocomplete, this is an example, it returns this output: "id, text, null (html I don't need), some html"
$response = array();
$names = array('Abraham Lincoln', 'Adolf Hitler', 'Agent Smith', 'Agnus', 'Etc');
// make sure they're sorted alphabetically, for binary search tests
sort($names);
$search = isset($_REQUEST['search']) ? $_REQUEST['search'] : '';
foreach ($names as $i => $name)
{
if (!preg_match("/^$search/i", $name)) continue;
$filename = str_replace(' ', '', strtolower($name));
$response[] = array($i, $name, null, '<img src="images/'. $filename . (file_exists('images/' . $filename . '.jpg') ? '.jpg' : '.png') .'" /> ' . $name);
}
header('Content-type: application/json');
echo json_encode($response);
I need a similar PHP to process this results: http://www.freebase.com/private/suggest?prefix=beatles&type_strict=any&category=object&all_types=false&start=0&limit=10&callback=
...being "beatles" the $search value, and getting this output:
guid,"name",null,"name<span>n:type name</span>"
So, the first result would be:
0,"The Beatles",null,"The Beatles<span>Band</span>"
Of course I would need to query freebase.com from that PHP. I mean:
+---------------+ +-----------+ +------------+
| | | | | |
| TextboxList +-------->| PHP +------->| Freebase |
| | | | | |
+---------------+ +-----------+ +------+-----+
|
JSON JSON |
TextboxList <--------+ freebase <----------+
Is this possible? Thanks!

Try this:
$response = array();
$search = isset($_REQUEST['search']) ? $_REQUEST['search'] : '';
$myJSON = file_get_contents('http://www.freebase.com/private/suggest?prefix=' . urlencode($search));
$musicObj = json_decode($myJSON); // Need to get $myJSON from somewhere like file_get_contents()
foreach ($musicObj->result as $item)
{
$response[] = array($item->guid, $item->name, null, $item->name . '<span>'.$item->{'n:type'}->name.'</span>');
}
header('Content-type: application/json');
echo json_encode($response);
The first JSON-escaped result then gives:
["#9202a8c04000641f800000000003ac10","The Beatles",null,"The Beatles<span>Band<\/span>"]
But despite all this, you really don't need to use PHP at all to do this. You can do this all from JavaScript and avoid an extra trip to your server. If you supply the callback argument to freebase, it can create JSONP (which is JSON wrapped in a call to a function, using a function name of your choice) which you can obtain in jQuery and then manipulate further in JavaScript to your liking. But the above is per your original approach in using PHP.

Related

Google Drive API advanced file search

I'm trying to develop a PHP script which goes through my Google Drive to list my files
. I have the current structure :
-- logo1.png
|
|-- logo2.png
|
-- myFolder
| |
| --logo3.png
|
|
-- myPrivateFolder
|
--logo4.png
I'm using the Google PHP library to make my queries. To list my files, I have this code :
$client = new Google_Client();
$client->setAuthConfig($oauth_credentials);
$client->setRedirectUri($redirect_uri);
$client->addScope("https://www.googleapis.com/auth/drive");
$service = new Google_Service_Drive($client);
$result = array();
try {
$parameters = array(
'q' => "mimeType contains 'image/'",
);
$files = $service->files->listFiles($parameters);
$result = array_merge($result, $files->getFiles());
} catch (Exception $e) {
print "Une erreur s'est produite : " . $e->getMessage();
}
return $result;
$result is an array of 4 elements. Since I specified I only want MIME type 'image/', I only get my 4 images. Now, I'd like to know, how can I filter my results to exclude my private directory from the research ? I want to be able to specify in which folder not to look ?
I wasn't able to find in the documentation anything about that. Thanks in advance for any help !
Firstly you'll need to get the ID of your private directory. You can do that with a query
name = 'my_private_directory'
Once you have the ID, you can extend your existing query with
and not 'xxxxxx' in parents where xxxx is the File ID from step 1.

Passing String Arrays into PHP file with Android

I'm trying to use retrofit and PHP to store values in MySQL. I will pass in to the PHP a single postid string (postid) and a string array. For each index in the string array (called tags) I will make a unique row in the database. It will have the following form:
--------------------
|postid | tags |
--------------------
| postid | tags[0]|
| postid | tags[1]|
| postid | tags[2]|
....................
--------------------
The issue I am having is that for the string array, only the last value in the array is being stored.
Here is the retrofit interface
#FormUrlEncoded
#POST("create_recipe.php")
Call<Void> createRecipe(
#Field("postid") String postid,
#Field("tags") String[] tags
);
and the retrofit client call
Retrofit retrofit = ApiClient.getClient();
ApiInterface apiService = retrofit.create(ApiInterface.class);
Call<Void> call = apiService.createRecipe(postid, tags);
call.enqueue(new Callback<Void>() {
#Override
public void onResponse(Call<Void> call, Response<Void> response) {
}
#Override
public void onFailure(Call<Void> call, Throwable t) {
}
});
Here is what the PHP that handles this looks like (excluding some of the init code)
if (isset($_POST['postid']) && isset($_POST['tags']){
$uid = $_POST['postid'];
$tags = array($_POST['tags']);
$tags_new = str_replace(array('[', ',', ']'), '' , $tags);
foreach ($tags_new as $value){
mysql_query("INSERT INTO Tags(postid, tag) VALUES('$postid', '$value')");
}
}
If I pass in postid = 30 and tags = {"milk", "cheese", "bread"} I want it to look like
--------------------
|postid | tags |
--------------------
| 30 | milk |
| 30 | cheese |
| 30 | bread |
....................
--------------------
but instead only bread will be stored.
How do I handle the string array passed in as a parameter in PHP?
What is the form of the array when I pass it onto $tags?
I had the same problem some time back and found no clear solution for it. However I built a simple solution for something similar. I hope this solution helps.
Actually, you can print it out in the PHP work sheet, you can add the following to log the input here.
file_put_contents("test.log",json_encode($_POST)."--".json_encode($_GET));
Only then will you be able to determine whether the array is correctly delivered to the php script.
you might want to reconsider about this, because the following line is basically just removing all the barriers in the string($tags, which is now interpreted as a String instead of an array):
$tags_new = str_replace(array('[', ',', ']'), '' , $tags);
and change it into
$tags_new = split(',' , $tags);

How to get values for a dynamically generated array in php

I am generating a dictionary in PHP where key and values are added to the dictionary.
But I am not able to fetch the values back. I am using following code:
//some code here
while (($line = fgets($fileServices)) !== false) {
//echo $line.'....................';
if (strpos($line,'header') == false){
$serviceName=explode(",", $line)[0];
$RestartData=explode(",", $line)[1];
$StatusData=explode(",", $line)[2];
$serviceRestartMappingdict[$totalServices]= $serviceName.':'.$RestartData;
$serviceStatusMappingdict[$totalServices]= $serviceName.'_'.$StatusData;
$totalServices = $totalServices+1;
}
}
$counter=0;
//echo $serviceStatusMappingdict[0];
fclose($fileServices);
$counter=0;
for ($i = 0; $i < count($serviceStatusMappingdict); ++$i){
echo '<<<<<<<<<<<<<<<<<<<<<<<'.$serviceStatusMappingdict[$i].'>>>>>>>>>>>>>>>>>>>>>>>>>>>';
}
If I do an echo like echo $serviceStatusMappingdict[0];, I get the value but when I use a loop to access the data I do not get any value.
[EDIT] The problem is coming because of the '<' character. Get rid of them and it will work straight away
To answer the following comments that have appeared, the characters '<' and '>' in combination in html refer to an opening and closure of a tag. ex: <div>
The problem comes because the browser is trying intrepreting it as an unknow element and does not know what to do with it. If you inspect the html code of the page you'll be able to see that the information is actually there, just not properly rendered.
[EDIT] Following Umpert parial answer, I tried this and it does the expected behavior. Can we have more informations on why it does not work in your case :
<?php
$array = array( '0' => "kakfa_ps -ef | grep kafka | grep server.properties",
'1' => "zookeeper_ps -ef | grep zookeeper | grep zookeeper.properties",
'2' => "schemaregistry_ps -ef | grep schema-registry | grep java",
'3' => "influx_/sbin/service influxdb status | grep active | grep running",
'4' => "mysql_/sbin/service mysql status | grep active | grep running",
'5' => "cassandra_/sbin/service cassandra status | grep active | grep exited",
'6' => "aerospike_/sbin/service aerospike status | grep active | grep running");
for($i=0;$i<count($array);++$i){
echo '<<<<<<<<<<<<<<<<<<<<<<<'.$array[$i].'>>>>>>>>>>>>>>>>>>>>>>>>>>>';
}
?>
Same amount of '<' and '>' as in your OP. Just to make sure.

php multi dimensional array's

I am pulling data out of a table that has these fields:
zipcode,city,state,county
My question is that some zip codes are in multiple cities, and some cities are in multiple zip codes... so is there a way to have all the data put into an array, then group all of the zip codes in order, then build a table out of that, so that it puts them in order, but if the data is redundant, like the zip, city, state and county are already in the array, then it skips it?
so then I can print it to the browser using echo, into a table like this:
74801 | Shawnee, Oklahoma | Pottawatomie
74801 | Bethel, Oklahoma | Pottawatomie
74801 | Johnson, Oklahoma | Pottawatomie
74851 | McLoud, Oklahoma | Pottawatomie
74851 | Dale, Oklahoma | Pottawatomie
etc.
But in the case of these:
74015 | CATOOSA, Oklahoma | Rogers
74015 | COTOOSA, Oklahoma | Rogers
Because those are duplicates in those fields (not in the rest of the table), I need it to skip showing it twice.
I think it is something like this:
$zipArray = array();
$zipCode = $dbhhandle->zip;
$cityName = $dbhhandle->city;
$countyName = $dbhhandle->county;
if($zipArray[$zipCode][$cityName] != $countyName) {
$zipArray[$zipCode][$cityName] = $countyName;
}
but I'm not sure if that is the right way to do it.
Then once I have the array built, how do I build the table?
Your code looks pretty close, but it's missing the state. So change the elements of the array into associative arrays with state and county elements.
Also, you need to check whether there's an entry for the zip code at all, before checking whether it's a duplicate, otherwise you'll access an undefined index.
$zipArray = array();
$zipCode = $dbhhandle->zip;
$cityName = $dbhhandle->city;
$countyName = $dbhhandle->county;
$stateName = $dbhandle->state;
if(!isset($zipArray[$zipCode][$cityName]) || $zipArray[$zipCode][$cityName]['county'] != $countyName) {
$zipArray[$zipCode][$cityName] = array('county' => $countyName, 'state' => $stateName);
}
To display the table, you use nested loops.
foreach ($zipArray as $zip => $cities) {
foreach ($cities as $city => $cityData) {
echo "<tr><td>$zip</td><td>$city, {$cityData['state']}</td><td>{$cityData['county']}</td></tr>";
}
}

Render XSL file to HTML using PHP

I need to read a excel (xls) file and render it to a HTML page.
I'm developing in PHP, using Symfony 2.6.5 and I want to have access to the excel cel data, in this way I can generate HTML in a Symfony Controller(or better in a a Template).
I'm using ExcelBundle and I've read the documentation, but I found only ways to set information and not to get.
Which is the best we to read the content of the excel?
PS: the excel is a price list in a tabular form like the follow:
+––––+––––––+–––––––––––––+–––––––+
| id | name | description | price |
|____|______|_____________|_______|
+––––+––––––+–––––––––––––+–––––––+
| 1 | foo | foo desc | 12€ |
+––––+––––––+–––––––––––––+–––––––+
| 2 | bar | abr desc | 65€ |
+––––+––––––+–––––––––––––+–––––––+
|... |... | ... | ... |
In according with the code source, simply pass the filename in the createPHPExcelObject method.
As Example:
public function xlsAction()
{
$filenames = "your-file-name";
$phpExcelObject = $this->get('phpexcel')->createPHPExcelObject($filenames);
foreach ($phpExcelObject ->getWorksheetIterator() as $worksheet) {
echo 'Worksheet - ' , $worksheet->getTitle();
foreach ($worksheet->getRowIterator() as $row) {
echo ' Row number - ' , $row->getRowIndex();
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(false); // Loop all cells, even if it is not set
foreach ($cellIterator as $cell) {
if (!is_null($cell)) {
echo ' Cell - ' , $cell->getCoordinate() , ' - ' , $cell->getCalculatedValue();
}
}
}
}
}
Simply pass the array to your view for rendering in the template.
Hope this help

Categories