I have set up HBase and trying to use Thrift-Php to upload an image and then display it. I have one table with one column family named info and used something like:
$tmpName=$_FILES["file"]["tmp_name"];
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);
try {
$mutations = array(
new Mutation( array(
'column' => 'info:pic',
'value' => $data
) ),
);
$client->mutateRow( $t, $username, $mutations );
} catch ( IOError $e ) {
echo( "expected error: {$e->message}\n" );
}
Which seems to work as it stores something in Hbase and then
$arr = $client->getRow($t, $username);
foreach ( $arr as $k=>$TRowResult ) {
$values = $TRowResult->columns;
asort( $values );
foreach ( $values as $k=>$v ) {
$usr= $v->value;
$content=$_GET['username'];
header('Content-type: image/jpg');
echo $usr;
}
}
But I get an error message saying that the image contains errors. Can someone provide an example in Php?
Thank you.
I think, your problem is that you use $data = addslashes($data); when you store data. There's no need to quote characters when storing them to HBase.
And, you can retrieve data like this:
$values = $TRowResult->columns;
$usr= $values['info:pic']->value;
$content=$_GET['username'];
header('Content-type: image/jpg');
echo $usr;
Related
I have the following data in a csv file.
I need to rearrange the data and concate it into 2 columns. the columns will be SKU and Feature. Where SKU = SKU and Feature will be derivative from other columns in the following format.
For yellow marked row: Feature column data will be: Edge:Square Edge;Wide Plank|Finish:Glossy;Smooth|Grade:A(Select & Better/Prestige)|Installation Location:Second Floor;Main Floor........
I could parse the csv and stucked.
$lines = explode( "\n", file_get_contents( '3b.csv' ) );
$headers = str_getcsv( array_shift( $lines ) );
$data = array();
foreach ( $lines as $line ) {
$row = array();
foreach ( str_getcsv( $line ) as $key => $field )
if($headers[$key]=='sku'){
$row[ $headers[ $key ] ] = str_replace(",",";",$field);
}
if($headers[$key]!='sku' && $field!='') {
$row['feature'] = $headers[ $key ].":".str_replace(",",";",$field)."|";
}
$row = array_filter( $row );
$data[] = $row;
}
echo "<pre>";
print_r($data);
echo "</pre>";
Anyone please help me to do this or suggest any script to do this.
You haven't provided the actual text of your incoming csv files, so I will assume that parsing it normally will work properly.
I have borrow my script from your next two questions to unconditionally process your data.
The header row's data is used as a lookup array for the feature names.
Code: (untested)
$file = fopen("3b.csv", "r");
$headers = fgetcsv($file);
$final_array = [];
while (($row = fgetcsv($file)) !== false) {
$sku = $row[0];
unset($row[0]);
foreach ($row as $featureNameIndex => $featureValues) {
foreach (explode(',', $featureValues) as $featureValue) {
$final_array[] = [
'sku' => $sku,
'feature' => "{$headers[$featureNameIndex]}:{$featureValue}"
];
}
}
}
fclose($file);
var_export($final_array);
This approach will generate an indexed array of associative arrays -- each containing two-elements.
Features with multiple values are divided and stored as separate subarrays.
I am attempting to get data from 3 separate CSVs and put the data into 3 separate arrays, in the code below the first 2 work fine, the third which is a clone of the second one with a few details changed doesn't... why?
How can I do get the third working too?
// First one
$awd_fp = fopen( 'https://example.com/test1.csv', 'r' );
$awd_stocks_temp = array();
while( $awd_row = fgetcsv( $awd_fp ) ) {
$awd_stocks_temp[] = $awd_row;
}
fclose( $awd_fp );
// Second one
$aeo_fp = fopen( 'https://example.com/test2.csv', 'r' );
$aeo_stocks_temp = array();
while( $aeo_row = fgetcsv( $aeo_fp ) ) {
$aeo_stocks_temp[] = $aeo_row;
}
fclose( $aeo_fp );
// Third one
$hb_fp = fopen( 'https://example.com/test3.csv', 'r' );
$hb_stocks_temp = array();
while( $hb_row = fgetcsv( $hb_fp ) ) {
$hb_stocks_temp[] = $hb_row;
}
fclose( $hb_fp );
echo '<hr>';
echo count( $awd_stocks_temp ) . ' / ';
echo count( $aeo_stocks_temp ) . '/ ';
echo count( $hb_stocks_temp );
echo '<hr>';
Your code is working perfectly fine it seems something's wrong with your csv file. Only thing I would suggest is instead of writing same code for reading csv file why don't you loop through it.
<?php
$files = array(
'test1.csv',
'test2.csv',
'test3.csv'
);
$stocks_temp = array();
$ctr = 0;
foreach($files as $file){
$fp = fopen( $file, 'r' );
while( $row = fgetcsv( $fp ) ) {
$stocks_temp[$ctr][] = $row;
}
fclose( $fp );
$ctr++;
}
// you will get all data in multidimensional array
echo "<pre>";
print_r($stocks_temp);
?>
I have a PHP file that grabs a .txt file and decodes the JSON to push the user's e-mail and name entry to my campaign monitor database. The JSON is wonky because new entries are added with a ][ as seen in this example:
[{"email":"drake.scott#test.com","createdate":"2016-03-23 10:44:52","from_email":null,"from_liked_pageid":null,"source":"direct","bonus_entry_url":"\/xxxbyn\/h1lvw5","entry_url":"https:\/\/admin.woobox.com\/manage\/offers\/entries\/20160314-1\/tu%2BcJmnsgyUxE7HM9BCqnRjnza27dGIdr%2BHymHrFmFoprsRgkhZradPrTJ5s18p6ewxYeOOKLpObd%2FWGAS%2BDRw%3D%3D","shareurl":"http:\/\/woobox.com\/qbxbyn\/h1lvw5","picked":"0","actionbutton":"","custom_3_first":"drake","custom_3_last":"scott","custom_4":"4146583264","fullname":"drake scott","id":"vvvbyn"}]
[{"email":"john.roberts#test.com","createdate":"2016-03-23 10:44:52","from_email":null,"from_liked_pageid":null,"source":"direct","bonus_entry_url":"\/xxx\/h1lvw5","entry_url":"https:\/\/admin.woobox.com\/manage\/offers\/entries\/20160314-1\/tu%2BcJmnsgyUxE7HM9BCqnRjnza27dGIdr%2BHymHrFmFoprsRgkhZradPrTJ5s18p6ewxYeOOKLpObd%2FWGAS%2BDRw%3D%3D","shareurl":"http:\/\/woobox.com\/vvvbyn\/h1lvw5","picked":"0","actionbutton":"","custom_3_first":"john","custom_3_last":"adams","custom_4":"4146585018","fullname":"john adams","id":"vvvbyn"}]
The problem I am having right now is uploading the entries to my database. I have managed to strip the ][ and doing a var_dump($content); shows a valid JSON string. However, doing var_dump($user) gives me 0 array(0) { }.
The entries will not upload to my database because there is essentially nothing in my array. Can anyone give me some insight on how to proceed?
<?php
require_once 'csrest_general.php';
require_once 'csrest_subscribers.php';
$auth = array(
'api_key' => 'xxxxxxxxxx');
$wrap = new CS_REST_Subscribers('xxxxxxxxxx', $auth);
$url = 'http://www.mywebsite.com/sweeps/test.txt';
$content = file_get_contents($url);
$content = str_replace('}][{', '},{', $content);
$tmp = explode('][', $content);
foreach ($tmp as $json_part) {
$user = json_decode('['.rtrim(ltrim($json_string, '['), ']').']', true);
$result = $wrap->add(array(
'EmailAddress' => $user->email,
'Name' => $user->fullname,
'Resubscribe' => true
));
}
if($result->was_successful()) {
echo "Subscribed with code ".$result->http_status_code;
}
else {
echo "failed";
var_dump($result->response);
var_dump($user);
}
?>
There are multiple JSON objects concatenated in the file. The easiest way to make the JSON valid is to create an array:
$content = str_replace('][', ',', $content);
$users = json_decode($content, true);
Then you have a multi-dimensional array with multiple users that you will need to decide what you want from it:
print_r($users);
foreach($users as $user) {
echo $user['email'] . "\n";
}
I'm trying to get data from an off-site Miscrosoft SQL database using php's odbc connection, convert certain queries against it to arrays, and then turn those arrays into a csv that my cms can read and import. I'm able to succesfully conncect and return some results from the database, but my lack of php and SQL skills is killing me.
What I have right now, which is not much, but does what it's supposed to do:
$result = odbc_tables($connect);
$tables = array();
while (odbc_fetch_row($result))
{
if(odbc_result($result,"TABLE_TYPE")=="TABLE")
echo"<br>".odbc_result($result,"TABLE_NAME");
}
Is there any clear resource on the web on how to do what I want to do? The official php documentation seems to be about the most unhelpful documentation ever. A basic example: I want to return the entries here into csv format. I can get them in array format:
$query = "SELECT TOP 10 * FROM Communities";
$result = odbc_exec($connect, $query);
if ( $result )
{
while ( ($row = odbc_fetch_array($result)) )
{
print_r($row);
}
odbc_free_result($result);
}
else
{
echo 'Exec error: ' . odbc_errormsg();
}
odbc_close($conn);
Wish I had more, but I'm a bit lost on where to go next.
Using the tips, here's the working solution:
$theArray = array();
while ( ($row = odbc_fetch_array($result)) )
{
array_push($theArray, $row);
}
$header = array('Name', 'Hours', 'Fees', 'Notes', 'ShortDescription', 'URL');
$fp = fopen('array.csv', 'w');
fputcsv($fp, $header);
foreach ($theArray as $lines)
{
fputcsv($fp, $lines);
}
I just got done doing the exact project that you are asking about. I am running php 5.2 so you may be able to deal with the csv file more easily in a newer version. Here is my code:
<?php
// Uncomment this line for troubleshooting / if nothing displays
ini_set('display_errors', 'On');
$myServer = "GSRBI";
$myUser = "webuser";
$myPass = "Webuser1";
$myDB = "GSRBI";
$dbhandle = odbc_connect($myServer, $myUser, $myPass)
or die("Couldn't connect to SQL Server on $myServer");
$return = odbc_exec($dbhandle, 'select * from GSRBI.dbo.BounceBackEmail');
$subscribers_array = array();
$db_row = '';
$arrayrow = 0;
while ( $db_row = odbc_fetch_array($return) )
{
$arrayrow++;
$array[] = array(
'card_num' => $db_row['PlayerAccountNumber']
,'last_name' => ucfirst(strtolower($db_row['LastName']))
,'first_name' => ucfirst(strtolower($db_row['FirstName']))
,'email' => $db_row['EMailAddress']
,'earned_on_date' => date('m/d/Y', strtotime('-1 days'))
,'free_play' => $db_row['Offer1']
,'valid_through_date' => date('m/d/Y', strtotime('+15 days'))
);
}
echo print_r($arrayrow, true); ## display number of rows for sql array
echo " rows in ODBC ";
// Creates an array with GSR webteams contact info
$array1[] = array(
'card_num' => "123456789"
,'last_name' => "GSRwebteam"
,'first_name' => "GSRwebteam"
,'email' => "webteam#something.com"
,'earned_on_date' => date('m/d/Y', strtotime('-1 days'))
,'free_play' => "9"
,'valid_through_date' => date('m/d/Y', strtotime('+15 days'))
);
$result = array_merge((array)$array, (array)$array1); ## merge the two arrays together
// This will convert the array to csv format then save it
## Grab the first element to build the header
$arr = array_pop( $result );
$temp = array();
foreach( $arr as $key => $data )
{
$temp[] = $key;
}
$csv = implode( ',', $temp ) . "\n";
$csv .= to_csv_line( $arr ); ## Add the data from the first element
foreach( $result as $arr ) ## Add the data for the rest
{
$csv .= to_csv_line( $arr );
}
//echo print_r($csv, true); ## Uncomment to test output1
$f = fopen('reports/bounceback-'.date('m-d-Y').'.csv', "w");
fwrite($f, $csv);
fclose($f);
Echo "The report has ran";
return $csv;
function to_csv_line( $result )
{
$temp = array();
foreach( $result as $elt )
{
$temp[] = '' . addslashes( $elt ) . '';
}
$string = implode( ',', $temp ) . "\n";
return $string;
}
I am getting back two rows from my query, I tested it in phpadmin.
In firebug I can only see the data from one row.
What could be wrong that I don't see?
$data = mysql_fetch_assoc($r);
}
}
header('Content-type: application/json');
$output = array(
"check" => $check,
"users" => $data,
"testnumberoffrows" => $number
);
echo json_encode($output);
in the ajaxfunction
if( data.check ){
var user = data.users;
console.log(user);
thanks, Richard
mysql_fetch_assoc() fetches only one row. You need to loop until it returns FALSE, building up an output array.
Something like this:
while (($row = mysql_fetch_assoc($r)) !== FALSE) {
$data[] = $row;
}
Please try
$got=array();
while ($row = mysql_fetch_array($r)) {
array_push($got, $row);
}
mysql_free_result($r);
header('Content-type: application/json');
$output = array(
"check" => $check,
"users" => $data,
"testnumberoffrows" => $number
);
echo json_encode($output);