PHP read and execute contents of a file as a string - php

I am trying to read a file as a string and return it to the client to be executed as javascript code in order to save it as a variable. Like so
<?php
$fileName = 'target.js';
$codeAsString = file_get_contents($fileName);
$script = 'var code=\'' . $codeAsString . '\'';
echo $script;
?>
Once returned, I want the variable code to have a string representation of the contents of target.js. However, it isn't working. I suspect it has to do with new line characters and single/double quotes... In Python they have a multi line quote
"""This
is
a "multi"
line
'quote'
"""
Is there anything like this in Javascript/php? I can't even wrap my head around whether I need the single quotes around $codeAsString when appending it to $script. Do I have to manually go in and prepend backslashes before all quotes, double quotes, back slashes...Surely they have helper functions for this
thanks.

json_encode is your friend...
<?php
$fileName = 'target.js';
$codeAsString = file_get_contents($fileName);
$script = 'var code= '.json_encode($codeAsString) .';';
echo $script;
?>

Use PHP function json_encode.

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.

PHP Missing Slashes

I am convinced that the solution is very simple, however I have searched many pages and questions and I am slightly frustrated with the lack of solution.
I'm trying to create a span element which has the onclick property.
The onclick event should pass to the displayStory function path to the text file.
Unfortunately, all slashes are missing.
Slashes are fine if I dont use apostrophes inside $dir, however i have to insert them somehow
PHP:
<?php
$allStories = scandir("./stories");
foreach($allStories as $story){
$dir = "'/stories/$story'";
$element = ("<span class='listElement' onclick='displayStory($dir)'>$story</span>");
echo $element;
}
?>
Output:
<span class="listElement" onclick="displayStory(" stories="" example.txt')'="">example.txt</span>
You need to learn how to escape characters:
<?php
$allStories = scandir("./stories");
foreach($allStories as $story){
// No single quotes here
$dir = "/stories/$story";
// No parenthesis needed to assign a value
// Escape double quotes for attributes preceding them with a backslash \"
// Use single quotes for function parameter
$element = "<span class=\"listElement\" onclick=\"displayStory('$dir');\">$story</span>";
echo $element;
}
?>
Output should be:
<span class="listElement" onclick="displayStory('stories/example.txt');">example.txt</span>

Removing all quotes from JSON file using PHP

I want to remove all double quotes from a JSON file using PHP.
The following code outputs all the variables to a JSON file named example.json:
$var_geoJSON = 'var geoJSON = ';
file_put_contents('jsonfun.json', $var_geoJSON);
file_put_contents('jsonfun.json', json_encode($geojson, JSON_NUMERIC_CHECK), FILE_APPEND);
I was trying to get it to output something like this:
var geoJSON = {...}
Yet it outputs something like this:
"var geoJSON = " {...}
I am currently working with geoJSON to output to the open source leaflet.js mapping library, and the syntax requires that I have var geoJson = {...} instead of having "var geoJSON = "{...}.
I have tried using the PHP command preg_replace() replacing all the "" with spaces, yet that still didn't work and it outputted the same thing with the double quotes.
Any ideas?
Just use str_replace function http://www.w3schools.com/php/func_string_str_replace.asp example:
$result = str_replace('"', '', $json)

php code inside variable with html code

I want to add code php to variable with html, for example
$html = '<b></b> <?php echo $lang["text"] ?>';
but it don't interpret php code. What am I doing wrong?
Use string concatenations like this:
$html = '<b></b>' . $lang['text'];
or insert variable in double quoted string like this:
$html = "<b></b>${lang['text']}";
both versions are correct, use the one that you like.
What you want is called string interpolation (read about how it works for PHP).
Your particular example would be solved using
$html = "<b></b> {$lang['text']}";
String interpolation only happens in double quoted string ("string here").
its very important to escape the output. (security basics)
$html = sprintf('<b>%s</b>', htmlspecialchars($lang['text']));
You can't switch from "Output raw text mode" to "Run PHP code mode" in the middle of a string while you are already in "Run PHP code mode"
$html = "<b></b> ${lang['text']}";
… although why you want an empty bold element is beyond me.
<?php
$html = '<b>'.$lang['text'].'</b>';
?>
make sure file extension is php.
<?php
$html = '<b>' . $lang["text"] . '</b>';
?>

magento escape string for javascript

Is there a helper function that will properly escape a string to be rendered as a single quote quoted JavaScript string literal?
I know of jsQuoteEscape but it only handles quotes and does not treat \n & \r etc.
so if my string is 'line1\nlineb' (i.e. two lines with a newline between them)
and I use
var jsvar='<?php echo $this->helper('myextension')->jsQuoteEscape($mystring); ?>';
I will get in the rendered content
var jsvar='line1
line2';
which is a syntax error.
Thanks,
Eyal
Yes
$string = 'Hello
There';
var_dump( Mage::helper('core')->jsonEncode($string) );
var_dump( json_encode($string) );
I've never been clear if this encoding a non-object string datatypes as a javascript string is a side-effect of the JSON encoding, or if it's true, according to Hoyle Crockford JSON, so I always like to wrap my strings in an object when passing them around
$o = new stdClass();
$o->param = 'This is my
Param';
$json = json_encode($o);
echo 'var data = ' . $json . ';' . "\n";
echo 'var jsdata = data.param';
This is how you'd handle this with javascript. There's no method that's build specifically for this. If you're interested in seeing the helper methods you do have available from a block, checkout the methods in
app/code/core/Mage/Core/Block/Abstract.php
app/code/core/Mage/Core/Block/Template.php
and if you're dealing with a template that's part of a block higher up the chain, get its class and then check its definition
var_dump get_class($this);

Categories