Get data with spaces from Google Spreadsheets (via PHP) - php

How I can get data from my Google Spreadsheet if it contains spaces?
Example: I have two columns: Person1 and Person2 and I need find a match names.
I read this Google API How to connect to receive values from spreadsheet
And tried:
$listFeed = $worksheet->getListFeed(array("sq" => "person1" . " = " . "Jon Doe"));
and it's not working. I also tried 'Jon%20Doe' but it's still not working. For rows without spaces in this field it works.

The expression "person1" . " = " . "Jon Doe" that you assign to the sq key in your array results in a "person1 = Jon Doe" string. Here it is likely that Jon Doe isn't seen as a string of its own, as you would like it to be.
Maybe you could try to quote Jon Doe like this:
$listFeed = $worksheet->getListFeed(array("sq" => "person1 = 'Jon Doe'"));
Or like this:
$listFeed = $worksheet->getListFeed(array("sq" => 'person1 = "Jon Doe"'));
Also, make sure the column parameter in your query string (here person1) is consistent with your column name (Person1). Case mismatch might be why it fails.

Related

How can print a json response with php

I'm building a simil web-service in php. This web service can read all record from a table of database and return a list of it in json format.
This is the code of my getArticoli.php file:
<?php
require_once('lib/connection.php');
$query_Articolo = "SELECT CodArticolo,NomeArticolo,Quantita,CodiceBarre, PrezzoAttuale, PrezzoRivenditore,PrezzoIngrosso
FROM VistaArticoli ";
$result_Articoli = $connectiondb->query($query_Articolo);
$answer = array ();
while ($row_Articoli = $result_Articoli->fetch_assoc()) {
$answer[] = ["id" => $row_Articoli['CodArticolo'],
"nome" => '"' . $row_Articoli['NomeArticolo'] . '"',
"quantita" => $row_Articoli['Quantita'],
"codiceBarre" => $row_Articoli['CodiceBarre'],
"codartFornitore" => $row_Articoli['CodiceBarre'],
"PrezzoAttuale" => $row_Articoli['PrezzoAttuale'],
"prezzoRivenditore" => $row_Articoli['prezzoRivenditore'],
"prezzoIngrosso" => $row_Articoli['prezzoIngrosso']];
}
//echo "fine";
echo json_encode($answer);
?>
Now, if I try to open this page, with this url: http://localhost/easyOrdine/getArticoli.php
I don't get the json_response.
In the table of database, there are 1200 records. If I try to insert an echo message in while cycle, I see it.
I have noticed that the problem lays with this field:
"nome"=>'"'.$row_Articoli['NomeArticolo'].'"'
If I remove this field from the response, I can correctly see the json response.
In this field there are any character from a-z/0-9 and special character like "/ * ? - and other".
It is possible that these special character can cause any error of the json answer?
EDIT
I have limit at 5 my query and this is the response:
[{"id":"878","0":"ACCESSORIO PULIZIA PUNTE DISSALDANTE 3 MISURE","quantita":"1","codiceBarre":"DN-705100","codartFornitore":"DN-705100","PrezzoAttuale":"14.39","prezzoRivenditore":null,"prezzoIngrosso":null},
{"id":"318","0":"ACCOPPIANTORE RJ11 TELEFONICO VALUELINE VLTP90920W","quantita":"20","codiceBarre":"5412810196043","codartFornitore":"5412810196043","PrezzoAttuale":"0.68","prezzoRivenditore":null,"prezzoIngrosso":null},
{"id":"320","0":"ACCOPPIATORE AUDIO RCA VALUELINE VLAB24950B","quantita":"5","codiceBarre":"5412810214136","codartFornitore":"5412810214136","PrezzoAttuale":"1.29","prezzoRivenditore":null,"prezzoIngrosso":null},
{"id":"310","0":"ACCOPPIATORE RJ45 VALUELINE VLCP89005W","quantita":"8","codiceBarre":"5412810228843","codartFornitore":"5412810228843","PrezzoAttuale":"0.38","prezzoRivenditore":null,"prezzoIngrosso":null},
{"id":"311","0":"ACCOPPIATORE USB2 VALUELINE VLCP60900B","quantita":"5","codiceBarre":"5412810179596","codartFornitore":"5412810179596","PrezzoAttuale":"1.80","prezzoRivenditore":null,"prezzoIngrosso":null}]
First, remove those extraneous quote characters. You don't need them and they could hurt you down the road:
while ($row_Articoli = $result_Articoli->fetch_assoc()) {
$answer[] = [
"id" => $row_Articoli['CodArticolo'],
"nome" => $row_Articoli['NomeArticolo'],
"quantita" => $row_Articoli['Quantita'],
"codiceBarre" => $row_Articoli['CodiceBarre'],
"codartFornitore" => $row_Articoli['CodiceBarre'],
"PrezzoAttuale" => $row_Articoli['PrezzoAttuale'],
"prezzoRivenditore" => $row_Articoli['prezzoRivenditore'],
"prezzoIngrosso" => $row_Articoli['prezzoIngrosso']
];
}
Then, run your query as is (without the LIMIT), and afterwards run echo json_last_error_msg()';, which could give you a hint to what's going on.
Also, being that your DB is in italian, maybe its encoding is not UTF-8. json_encode requires UTF-8 encoded data. So you may try to utf8_encode your article names before json_encoding the array:
"nome" => utf8_encode($row_Articoli['NomeArticolo']),
And see what you get.
Changing your DB charset to 'utf8mb4' could do the trick as well, and it is usually recommended.

Swiftmailer rejecting valid email addresses if and only if submitted in array

I'm pulling users' phone numbers from an s2member database and appending the wireless carrier domain name required to send SMS texts via email (Swift Mailer). So to create the array of email addresses I use the following (the function cellmap below just replaces the users' wireless carrier with the correct domain to append):
$matches = array();
if (is_array ($users) && count ($users) > 0) {
foreach ($users as $user) {
$user = new WP_User ($user->ID);
$matches[] = "'" . get_user_field("cell_no", $user->ID) . cellmap(get_user_field("cell_carrier",$user->ID)) . "'";
}
}
The resulting array looks like this, for an example of 4 matched users:
Array
(
[0] => '1234567891#vtext.com'
[1] => '3216549871#vtext.com'
[2] => '9876543211#vtext.com'
[3] => '6543219877#vtext.com'
)
Then I implode to create a string to use as the "To" field for Swift Mailer:
$cell_list = implode(", ", $matches);
which results in this (numbers are made up):
'1234567891#vtext.com', '3216549871#vtext.com', '9876543211#vtext.com', '6543219877#vtext.com'
Now I pass that to Swift Mailer like so:
$outgoing_message = Swift_Message::newInstance('')
->setFrom(array('no-reply#mydomain.com' => 'Mydomain'))
->setTo($cell_list)
->setBody($message);
// Send the message
$result = $mailer->send($outgoing_message);
And I get this error (ignore the phone numbers: they're made up, but correspond to the right ones in practice):
PHP Fatal error: Uncaught exception 'Swift_RfcComplianceException' with message 'Address in mailbox given ['123456789#vtext.com', '987654321#vtext.com', '5555551212#vtext.com', '321654987#vtext.com'] does not comply with RFC 2822, 3.6.2.'
I can successfully send any one of these emails individually via Swift Mailer, but when they appear as an array I always get the above error. I have tried applying trim to the individual addresses and the entire resulting string. A print_r of the array does not show any non-printable characters. I have tried various combinations of ->setTo($cell_list), ->setTo(array('$cell_list')) and anything else that might work, to no avail. I have tried replacing comma with semicolon in the list, and removing the single quotes around each address. As far as I can tell, the string of email addresses is in the exact format as shown in the Swift Mailer documentation. For the life of me I can't figure this out.
According to Swiftmailer documentation, setTo takes either a single email address or an array of email addresses as parameter.
Your code:
$cell_list = implode(", ", $matches);
$outgoing_message = Swift_Message::newInstance('')
->setFrom(array('no-reply#mydomain.com' => 'Mydomain'))
->setTo($cell_list)
->setBody($message);
Using implode() puts all the email addresses in a single string of text.
I suggest not imploding $matches:
$outgoing_message = Swift_Message::newInstance('')
->setFrom(array('no-reply#mydomain.com' => 'Mydomain'))
->setTo($matches)
->setBody($message);

PHP array custom format

I am just starting on the PHP.
I am working on getting information from WordPress database.
The plugin writes data to a DB, from the Sign up form.
What I want is to get this data formatted on my own way, let's say a table, on a separate page.
So what I did already, is to connect to a DB, and print the data. Did it by this:
<?php
//connect to the database
mysql_connect ("host","user","pasw") or die ('Cannot connect to MySQL: ' . mysql_error());
mysql_select_db ("database") or die ('Cannot connect to the database: ' . mysql_error());
//query
$query = mysql_query("select id, data from wp_ninja_forms_subs") or die ('Query is invalid: ' . mysql_error());
//write the results
while ($row = mysql_fetch_array($query)) {
echo $row['id'] . " " . $row['data'] . "
";
// close the loop
}
?>
The thing is, that I get the results, which doesn't really suit me:
14 a:4:{i:0;a:2:{s:8:"field_id";i:2;s:10:"user_value";s:8:"John Doe";}i:1;a:2:{s:8:"field_id";i:4;s:10:"user_value";s:11:"+3706555213";}i:2;a:2:{s:8:"field_id";i:12;s:10:"user_value";s:9:"Company 1";}i:3;a:2:{s:8:"field_id";i:8;s:10:"user_value";a:1:{i:0;s:13:" Finansiniai ";}}} 15 a:4:{i:0;a:2:{s:8:"field_id";i:2;s:10:"user_value";s:10:"Bill Gates";}i:1;a:2:{s:8:"field_id";i:4;s:10:"user_value";s:11:"+5654412213";}i:2;a:2:{s:8:"field_id";i:12;s:10:"user_value";s:9:"Company 2";}i:3;a:2:{s:8:"field_id";i:8;s:10:"user_value";a:1:{i:0;s:13:" ?vaizd˛io ";}}} 16 a:4:{i:0;a:2:{s:8:"field_id";i:2;s:10:"user_value";s:7:"Person3";}i:1;a:2:{s:8:"field_id";i:4;s:10:"user_value";s:7:"6463213";}i:2;a:2:{s:8:"field_id";i:12;s:10:"user_value";s:9:"Company 3";}i:3;a:2:{s:8:"field_id";i:8;s:10:"user_value";a:2:{i:0;s:10:" HTML/CSS ";i:1;s:12:" Photoshop ";}}} 17 a:4:{i:0;a:2:{s:8:"field_id";i:2;s:10:"user_value";s:11:"Pretty Girl";}i:1;a:2:{s:8:"field_id";i:4;s:10:"user_value";s:9:"643122131";}i:2;a:2:{s:8:"field_id";i:12;s:10:"user_value";s:4:"Zara";}i:3;a:2:{s:8:"field_id";i:8;s:10:"user_value";a:1:{i:0;s:13:" ?vaizd˛io ";}}}
Now, what I want to see is a table:
2013.10.25 Pretty Girl 643122131 Zara Įvaizdžio
2013.10.25 Person3 6463213 Company 3 HTML/CSS , Photoshop
2013.10.25 Bill Gates +5654412213 Company 2 Įvaizdžio
2013.10.25 John Doe +3706555213 Company 1 Finansiniai
Could someone tell me, how to achieve that?
I believe, that my data output is an array, or am I wrong about it too?
If yes, maybe someone could give me an example how to format one part of that array, so I could do the rest?
Or even some hint on what to google for?
Thanks!
Use "\n" for new line character :)
Your individual values (a:4:{i:0....}) have been "serialized". This one was an array of four elements that was passed to the serialize() PHP function. The function returned it's textual representation (i.e. it has "serialized" the array). So you have the entire array saved in one cell in database as simple text.
Function unserialize() does the opposite - turns the "serialized" (text) values and returns the original PHP object (an array in this case).
You can serialize almost any PHP object as long as it doesn't have some any "resources" attached to it. But there is already a separate question for that: What could cause a failure in PHP serialize function?
As long as you serialize arrays of numbers, strings and arrays and even simple objects there is nothing to worry about.
Your first cell (no 14) when unserilalized:
array (
0 =>
array (
'field_id' => 2,
'user_value' => 'John Doe',
),
1 =>
array (
'field_id' => 4,
'user_value' => '+3706555213',
),
2 =>
array (
'field_id' => 12,
'user_value' => 'Company 1',
),
3 =>
array (
'field_id' => 8,
'user_value' =>
array (
0 => ' Finansiniai ',
),
),
)
(Using: http://www.functions-online.com/unserialize.html) Run these trough a for loop or something to get the rendering you need, that's up to you.

PHP Multi Dimensional Array : Phone Prefix vs Courier Name

I'm thinking to use Array to store this tiny data instead using Database. But, I have difficulties to 'call' the data since this is Multi Dimensional Array.
Here's my situation :
I have several phone prefix from different cities :
$CityA = array("021","031","041","051");
$CityB = array("011","012","013","014");
$CityC = array("111","112","113","114");
Also, I have several courier for those cities :
$CityA = array("FedEx", "TNT", "DHL");
$CityB = array("YYY Cargo", "USPS");
$CityC = array("UPS", "Regular Mail", "XXX Cargo");
what I need is :
INPUT : Phone Prefix, for example 021
OUTPUT : FedEx, TNT or DHL >> Randomly selected
here's another examples :
012 >> YYY Cargo (Randomly selected from "YYY Cargo", "USPS")
112 >> UPS
etc.
It's pretty easy with MySQL, but I want to reduce database connection by using Array. how to do this?
You should use associative arrays for easier access. Since you want to access info by phone prefix, you should use these as keys for the first array. Then, your second array can be indexed by city, as below:
$cities = array( 021 => "CityA", 031 => "CityA", 011 => "CityB")
$couriers = array( "CityA" => array("FedEx", "TNT", "DHL"),
"CityB" => array("YYY Cargo", "USPS"),
"CityC" => array("UPS", "Regular Mail", "XXX Cargo"));
So, in your example, for retrieving a courier for prefix 021 you can acces it like this:
$city = $cities[$phone_prefix];
$courier_key = array_rand($couriers[$city]);
$courier_name = $couriers[$city][$courier_key];
So you want to specify an area code from "area-code array A", and then generate a random courier from "courier array A"?
Quick and dirty, but you could generate a random number between 0 and count($couriersA) - 1 (the number of entries in that array) and then select that entry in the array.
If not, you could look at combinations - so getting all the possible pairs of area code and courier, then choosing one randomly from that.
Try this code. You will get random courier for City code ( $value='111'; )
$CityA = array("021","031","041","051");
$CityB = array("011","012","013","014");
$CityC = array("111","112","113","114");
$courierA = array("FedEx", "TNT", "DHL");
$courierB = array("YYY Cargo", "USPS");
$courierC = array("UPS", "Regular Mail", "XXX Cargo");
$value = '111'; // Your City Code
if(in_array($value, $CityA)){
shuffle($courierA);
echo $courierA[0];
}
else if(in_array($value, $CityB)){
shuffle($courierB);
echo $courierB[0];
}
else if(in_array($value, $CityC)){
shuffle($courierC);
echo $courierC[0];
}
Output: YYY Cargo or USPS

PHP + PDO, my escaped characters won't show when displayed

First, I'd like to apologize, I'm still a beginner.
For learning purposes I'm creating a blog engine and I just noticed that when I list the comments, escaped characters like carriage return (pressing enter) are shown in the database correctly, but only a whitespace character when displaying the comments.
I'm using PostgreSQL 8.3.
Here you can see an example database entry:
fema=> select * from comments where id = 54;
-[ RECORD 1 ]-------------------------
id | 54
authorid | 1
text | This new line won't show.\r
: No\r
: \r
: new\r
: \r
: \r
: \r
: lines.
time | 1341417673
postid | 15
answerid | 0
Here you can see what var_dump() shows:
string(50) "This new line won't show. No new lines."
This is how I'm getting the data:
$stmt = db::$db->prepare("select comments.id as commentid ,authorid,text,time,postid,answerid,users.* from comments left join users on users.id = comments.authorId where postid = :postId");
$stmt->execute(array('postId' => $_GET['p']));
$commentRslt = $stmt->fetchAll();
Then foreach to iterate through them and replace the mark I'm using to identify things I have to replace:
$currComment = str_replace('{{{cms:comment:text}}}', $commentRslt[$key]['text'], $currComment);
This is how I insert the new comment to the DB:
$stmt = self::$db->prepare('INSERT INTO comments (authorId, text, time, postId, answerId) VALUES (:authorId, :text, :time, :postId, :answerId)');
$stmt->execute(array( 'authorId' => $_SESSION['userId'],
'text' => str_replace(array('<','>'), array('&lt','&gt'), isset($_POST['newCommentArea']) ? $_POST['newCommentArea'] : $_SESSION['newCommentArea']),
'time' => time(),
'postId' => isset($_POST['commentNew']) ? $_POST['commentNew' ] : $_SESSION['postId'],
'answerId' => $answerId));
Sorry for the many code samples, but I don't even know where the problem is and I wanted to be thorough.
So could anyone please tell me how to solve the problem? If only just by telling me where I made the mistake. I really have no clue.
Thanks.
Jut guessing here, but:
Consecutive whitespace is collapsed to a single space by HTML/the browser. Replace newlines with <br> tags if you want to keep them, using nl2br.

Categories