double quotes in mysql data not working for json - php

I have code like
$m_strOutput= "{\"success\":true,\"results\":" . $m_objQuery->num_rows() . ",\"rows\":";
$m_strOutput = $m_strOutput . json_encode($m_objQuery->result());
$m_strOutput = $m_strOutput . "}";
But some data already has double quotes in it. So it breaks my views where i try to parse it. How do i solve this double quotes problem.

Two things:
This is not a problem of double quote. You'll have syntax error to put a value into a JSON object without a key.
You should let json_encode do all the jobs for you.
Codes that might fit your case:
<?php
$m_strArr = array(
'success' => true,
'results' => $m_objQuery->num_rows(),
'rows' => $m_objQuery->result(),
);
$m_strOutput = json_encode($m_strArr);
?>

Related

How do I remove quotation from csv?

How do I remove quotation from csv?
Code
use Goutte\Client;
$client = new Client();
$response = $client->request('GET', 'http://c-manage.herokuapp.com/login');
$login_form = $response->filter('form')->form();
$login_form["account"] = '1';
$login_form["password"] = 'rpa1001';
$client->submit($login_form);
$client->request('GET', 'http://c-manage.herokuapp.com/client/download?searchQuery%5Bstatus%5D=1&searchQuery%5BregisterStartDate%5D=2010-01-01&searchQuery%5BregisterEndDate%5D=2020-01-01');
$csvResponse = $client->getResponse()->getContent();
return $csvResponse;
response is ...
ID,ステータス,分類,名前,名前(カナ),誕生日,郵便番号,住所,メールアドレス,電話番号,FAX,メモ,登録日,更新日\r\n
213,契約中,個人,"鶴田 秀夫","ツルタ ヒデオ",2000/07/24,1508207,神奈川県吉田市北区佐々木町小林7-4-5,hiroshi.nakatsugawa#yamaguchi.net,0310-282-609,0730-327-581,,"2010-01-25 00:00:
00","2010-01-25 00:00:00"\r\n
221,契約中,個人,"桑原 彩羅","クワハラ サイラ",2008/04/03,8103797,青森県杉山市西区石田町浜田3-4-10,vwakamatsu#kiriyama.jp,090-5710-4350,03849-5-5746,,"2010-01-09 00:00:00","2010-0
1-09 00:00:00"\r\n
237,契約中,個人,"堤 悟志","ツツミ サトシ",2001/04/29,6875750,栃木県佐々木市東区中島町浜田6-6-6,xtsuda#suzuki.com,022-557-4260,0573-01-2822,,"2010-02-07 00:00:00","2010-02-07 00:0
0:00"\r\n
273,契約中,個人,"富永 圭三","トミナガ ケイゾウ",2003/03/16,6314524,静岡県若松市東区廣川町青山10-9-6,yamaguchi.takuma#kondo.com,0020-062-493,06-3862-0779,,"2010-02-13 00:00:00","2
010-02-13 00:00:00"\r\n
.
.
.
What I want to do
I want to remove quotation from csv.
not
213,契約中,個人,"鶴田 秀夫","ツルタ ヒデオ",2000/07/24,1508207,
but
213,契約中,個人,鶴田 秀夫,ツルタ ヒデオ,2000/07/24,1508207,
※This personal information is fake.
What I did
str_replace(""", "", $csvResponse);
str_replace("\xEF\xBB\xBF", '', $csvResponse);
but, not working
The quotes serve a purpose here so you shouldn't be removing them haphazardly. The quotes prevent columns from breaking when they need to contain text that can also contain the delimiter. Like "Foo, bar, baz" for example. Removing the quotes turns this one column into 3 columns, which is obviously wrong.
Though, if you did want to remove them str_replace would certainly not be the way to go, because the quotes can be escaped to be literals inside the column. For example, using str_replace on this column: "He said \"this is crazy\", and left." would strip literals from the column value.
Instead you should load the CSV data with fgetcsv() or str_getcsv() and rebuild the CSV without the quotes like so...
foreach (str_getcsv($csvData) as $row) {
echo implode(",", $row), "\n";
}
This will give you back the literal values of each row without the quotes. Though any literal quotes inside those values will become quotes.

Joining variable to strings fails in PHP

I'm sorry that this is basic. When I use this PHP code it works fine:
$data = '{"reportID":1092480021}';
However, when I run my URL like this:
http://localhost:8000/new/reportget.php?type=1092480021
and use this PHP code:
$reportref = $_GET['type'];
$data = '{"reportID:".$reportref."}"';
I get the error
Error_description:reportID is required
I think it's an error with how I am joining my variable to the string but I can't understand where I am going wrong.
Your string is improperly quoted. To match the format in your first example use:
$data = '{"reportID":' . $reportref.'}';
Note there are no double quotes on the last curly.
Even better:
$reportref = 1092480021;
$data = [ 'reportId' => $reportref ];
var_dump(json_encode($data));
Output:
string(23) "{"reportId":1092480021}"
For simple view and understanding, can you try out:
$data = "{\"reportID\":$reportref}";
Think that should sort it out
Use it like this
data = '{"reportID:"'.$reportref.'"}"';
It isn't working because you wrap all the value within single quote and when it come to concatenate the $reprtref you put directly .$reportref without closing the first single quote and after putting the value to concatenate you forget to open another single quote
'{"reportID:".$reportref."}"';
the correct value is
'{"reportID:"' . $reportref . '"}"';
and to match the way you specify your $data value It must be like this
'{"reportID":' . $reportref . '}';

Writing string to screen without quotes in php

I am trying to write string to screen without quotes in php. I get the string data from a Mysql database and I try to write it to a textbox but double quotes are also written.
Example : "a2" .
i want that just write => a2 .
$gönder= (json_encode($gönder) );
echo $gönder;
string data is $gönder .
Use it like this :
echo trim($gönder, '"');
Since $gönder is a string, json_encode($gönder) will wrap it in double quotes.
Just echo it before applying json_encode:
$gönder = 'a2';
echo $gönder; // a2
$gönder = json_encode($gönder);
echo $gönder; // "a2"
use this code
echo trim($gönder, '"');

Enclose PHP output in quotation marks

we have a PHP script that exports orders to .csv files. The system we are exporting too requires each field to be encapsulated in quote marks.
Here is the code where we set each field.
$order_data = array(
'type' => "H",
'order_type' => 'HOME',
'order_date' => $order->order_date,
'account_code' => "REAL",
'document_reference' =>'',
'reference1'=>'',
'reference2'=>'',
'delivery_addess_code'=> '',
'billing_first_name' => $order->billing_first_name ." ".$order->billing_last_name,
'billing_address_1' => $order->billing_address_1 ." ".$order->billing_address_2,
'billing_postcode' => $order->billing_postcode,
'delivery_tel_no'=> $order->billing_phone,
'delivery_contact'=> $order->billing_first_name,
This outputs;
H,HOME,"2015-05-13 13:19:46",REAL,,,,,"Ben Bull","Address 1 Address2",
Some are surround by "" and some aren't how do we get them all to be?
For CSV output, you need to enclose all the values with double quotes. In addition, if the values have double quotes inside them you need to escape those double quotes by using two consecutive double quotes. That's how CSV works.
Check this PHP function below.
function makeCSV($value) {
//Encloses each token (Before and after)
$CSV_TOKEN_ENCLOSER = '"';
//Used to escape the enclosing character if inside the token
$CSV_TOKEN_ENCLOSER_ESCAPER = '""';
//Escape the encloser inside the value
$csv_value = str_replace($CSV_TOKEN_ENCLOSER, $CSV_TOKEN_ENCLOSER_ESCAPER, $value);
//Enclose the value
$csv_value .= $CSV_TOKEN_ENCLOSER . $csv_value . $CSV_TOKEN_ENCLOSER;
//Return
return $csv_value;
}
This does the job as I've explained in the first paragraph. You can use it as such in your case:
$order_data = array(
'type' => makeCSV("H"),
'order_type' => makeCSV('HOME'),
'order_date' => makeCSV($order->order_date),
...
);
However, it looks like you have code that's enclosing the values from your order objects within quotes automatically for you. I suggest you avoid that code, replace that with the usage of the makeCSV function presented above, and then finally just use a standard PHP implode call to get your CSV like this:
$comma_separated_csv = implode(",", $order_data);
Hope this helps.
Cheers.
Try to force all types to string like:
'order_type' => (string) 'HOME'

PHP making an URL link work inserting the $variables the right syntax way

I have this link that works.
echo '<a href="?country=Estonia&from_language=Russian&into_language=Latvian&submitted=true&
page='.$x. '">'.$x.'</a> ';
But I need the nouns Estonia, Russian and Latvian replaced by scalar variables like $country, $from_language, $into_language.
I have tried all possible combinations of dots and single and double quotes. I always get syntax errors. I don't know how the embed the variables there.
Anybody knows?
thank you
Do yourself a massive favour and use http_build_queryDocs:
<a href="?<?php echo http_build_query(array(
'country' => $country,
'fromLanguage' => $fromLanguage,
'somethingElse' => $somethingElse,
'...' => '...'
), '', '&'); ?>">Link</a>
use something easy one like sprintf or printf.
eg:
printf('<a href="?country=%s&from_language=%s&into_language=%s&submitted=true&
page=%s">%s</a>', $country, $fromLanguage, $toLanguage, $pageID, $dispText);
You could also use something like encoding with double quote sign like:
echo "<a href=\"?country={$country}&from_language={$fromLanguage}&into_language={$toLanguage}&submitted=true&
page={$pageID}\">{$dispText}</a>"
Avoid to put variables directly into string when not extremely simple. Use concatenation instead, and escape string if you want to make something good:
echo '<a href="?country=' . htmlentities($country) .
'&from_language=' . htmlentities($from_language) .
'&into_language=' . htmlentities($into_language) .
'&submitted=true&page=' . intval($x) . '">' . htmlentities($x) . '</a> ';
Anyway, if you really want it the complex way, you have to consider that you need doble quotes for HTML attributes, but double quotes are needed to wrap the PHP string because you want to put variables in it. So, you must escape HTML double quotes. Try:
echo "' . $x . ' ';
Combining the answers of Corbin and KoolKabin gives you this easy-to-read snippet:
printf('%s',
htmlspecialchars(
http_build_query(array(
'country' => $country,
'from_language' => $from_language,
'into_language' => $into_language,
'submitted' => 'true',
'page' => $x
))
),
htmlspecialchars($x));
Parametrization
printf and sprintf are very useful for adding parameters to strings. They make it easy to add escaping or complex values without making the string itself unreadable. You can always see at a glance what string it is by the first parameter.
http_build_query is also a way of parametrizing, but for the querystring. The main use is that you don't need to focus on the syntax of querystrings at all.
Escaping
htmlspecialchars makes sure that the data is fit for insertion into HTML code. It's similar to escaping in SQL queries to avoid SQL injections, only here we want to avoid HTML injections (also called XSS or cross-site scripting).
http_build_query will automatically make sure that all values are escaped for insertion as an URL in the address field in a browser. This does not guarantee fitness for insertion into HTML code. htmlspecialchars is therefore needed for the querystring as well!
If you scripts output HTML, consider to configure the output setting for argument separators arg_separator.output:
ini_set('arg_separator.output', '&');
You can then simply create the URI query info path by using http_build_query:
$country = 'de';
$fromLanguage = 'en_EN';
?>
Link
Which will give you a perfectly validly encoded output, which is immune to injections:
Link
Full Demo
$country = 'Estonia';
$from_language = 'Russian';
$into_language = 'Latvian';
echo ''.$x.' ';
OR
echo "$x";
OR
echo "{$x}";

Categories