magento escape string for javascript - php

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);

Related

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 - HTML characters posted within Tweet status

When using Abrahams/TwitterOAuth library, special HTML characters are placed in a Tweet.
$content = "test's";
$params = array(
"status" => $content
);
$result = $connection->post("statuses/update", $params);
results in
test's
within the posted Tweet status.
A vardump($content) in the browser reveals test's as expected.
I've tried html_entity_decode and htmlspecialchars_decode but neither work for the posted Tweet.
You need to tell it explicitly to convert the quotes. This is done with ENT_QUOTES.
Example:
echo htmlspecialchars_decode('test's',ENT_QUOTES) . "\n";
echo htmlspecialchars_decode('test's');
Output:
test's
test's
Demo: https://eval.in/426992
There are also other constants that can be used if you only want to decode single quotes etc. See the manual for more information, http://php.net/manual/en/function.htmlspecialchars-decode.php.
ENT_QUOTES Will convert both double and single quotes.
$content = "test's";
$content = htmlspecialchars_decode($content, ENT_QUOTES);
works for me.
Thanks chris85!

SimpleXMLElement using a string

I want to create a new SimpleXMLElement with data . When I put the data from the link below in the code I get the next error: Fatal error: Uncaught exception 'Exception' with message 'String could not be parsed as XML
The encoded data can be found here:http://www.interwebmedia.nl/dataxi/base64.txt
decoded data: http://www.interwebmedia.nl/dataxi/data.txt
<?php
str = 'encodeddata';
//echo htmlspecialchars(base64_decode($str),ENT_QUOTES);
$decoded = htmlspecialchars(base64_decode($str),ENT_QUOTES);
$xml = new SimpleXMLElement($decode);
echo $xml->asXML();
?>
I think you've attempted to use HEREDOC syntax (or seen somebody else using it) but completely misunderstood it.
HEREDOC syntax is an alternative way of quoting a string, instead of " or '. It's useful for hard-coding blocks of XML, because it acts like double-quotes, but let's you use double-quotes inside, like this:
$my_xml_string = <<<XML
<some_xml>
<with multiple_lines="here" />
</some_xml>
XML;
That code is precisely equivalent to this:
$my_xml_string = "
<some_xml>
<with multiple_lines=\"here\" />
</some_xml>
";
What you have done instead is taken the literal string "<<<" and added it onto your XML, giving you a string like this:
$my_xml_string = "<<<XML
<some_xml>
<with multiple_lines=\"here\" />
</some_xml>
XML";
Or in your example, the string "<<<XML<data>XML".
As far as the XML parser's concerned, you've just put a load of garbage on the beginning and end of the string, so it rightly complains it's not a valid XML document.

simplexml_load_string and the unwelcome parse error

Update: Casting as an array does the trick. See this response, since I don't have enough clout to upvote :)
I started on this problem with many potential culprits, but after lots of diagnostics the problem is still there and no obvious answers remain.
I want to print the placename "Gaborone", which is located at the first tag under the first tag under the first tag of this API-loaded XML file. How can I parse this to return that content?
<?php
# load the XML file
$test1 = (string)file_get_contents('http://www.afdb.org/fileadmin/uploads/afdb/Documents/Generic-Documents/IATIBotswanaData.xml');
#throw it into simplexml for parsing
$xmlfile = simplexml_load_string($test1);
#output the parsed text
echo $xmlfile->iati-activity[0]->location[0]->gazetteer-entry;
?>
Which never fails to return this:
Parse error: syntax error, unexpected '[', expecting ',' or ';'
I've tried changing the syntax to avoid the hyphens in the tag names as such:
echo $xmlfile["iati-activity"][0]["location"][0]["gazetteer-entry"];
. . . but that returns complete nothingness; no error, no source.
I've also tried debugging based on these otherwise-helpful threads, but none of the solutions have worked. Is there an obvious error in my simplexml addressing?
I've tried changing the syntax to avoid the hyphens in the tag names
as such: echo
$xmlfile["iati-activity"][0]["location"][0]["gazetteer-entry"];
Your problem here is that, object native casting to an array isn't recursive, so that you did that for primary keys only. And yes, your guess is correct - you shouldn't deal with object properties when working with returned value of simplexml_load_string() because of the syntax issues. Instead, you should cast a returned value of it (stdclass) into an array recursively. You can use this function for that:
function object2array($object) {
return json_decode(json_encode($object), true);
}
The rest:
// load the XML file
$test1 = file_get_contents('http://www.afdb.org/fileadmin/uploads/afdb/Documents/Generic-Documents/IATIBotswanaData.xml');
$xml = simplexml_load_string($test1);
// Cast an object into array, that makes it much easier to work with
$data = object2array($xml);
$data = $data['iati-activity'][0]['location'][0]['gazetteer-entry']; // Works
var_dump($data); // string(8) "Gaborone"
I had a similar problem parsing XML using the simpleXML command until I did the following string replacements:
//$response contains the XML string
$response = str_replace(array("\n", "\r", "\t"), '', $response); //eliminate newlines, carriage returns and tabs
$response = trim(str_replace('"', "'", $response)); // turn double quotes into single quotes
$simpleXml = simplexml_load_string($response);
$json = json_decode(json_encode($simpleXml)); // an extra step I took so I got it into a nice object that is easy to parse and navigate
If that doesn't work, there's some talk over at PHP about CDATA not always being handled properly - PHP version dependent.
You could try this code prior to calling the simplexml_load_string function:
if(strpos($content, '<![CDATA[')) {
function parseCDATA($data) {
return htmlentities($data[1]);
}
$content = preg_replace_callback(
'#<!\[CDATA\[(.*)\]\]>#',
'parseCDATA',
str_replace("\n", " ", $content)
);
}
I've reread this, and I think your error is happening on your final line - try this:
echo $xmlfile->{'iati-activity'}[0]->location[0]->{'gazetteer-entry'};

PHP read and execute contents of a file as a string

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.

Categories