json_decode with values containing double quotes - php

I am trying to use an editable table and have it working except for when the array values passed to the save function contain double quotes. The error occurs at foreach loop
foreach($saveArray as $rowId=>$row) {
It is the values (not keys) which may contain double quotes, the actual error being:
Warning: Invalid argument supplied for foreach()
What is the best way around this, some way to escape them, change them to the &quot code, change the way the loop works?
EDIT:
Sorry, the problem is actually with the json_decode function and double quote values, not returning an array.
Works fine for non double quoted entries
json looks like
{"2":{"component":"8\"", ...
So it is escaped but it's not decoding into an array

See what $saveArray actually is, using
var_dump($saveArray)
It doesn't look like your $saveArray, whatever it is, supports the foreach construct.
If $saveArray comes from json_decode(), it's likely that your JSON string is invalid, and json_decode() just returns NULL.

Related

Will php's json_encode() always use double quotes as string delimiter?

I have a php associative array containing strings as values and I encode it to JSON and store it in an html-data attribute. That is read by some JS.
So far so good.
Now, I need to use single quotes for the data attribute, otherwise the context switches.
<section id="settings" data-settings='{"some":"val"}'>
</section>
The question is, can I rely on the json_encode() function of php to encode strings always with double quotes? Surprisingly, I can't seem to find information on this. I only find articles from people having issues with quotes in the array values.
Thanks in advance.
Yes, as defined in the JSON spec, the delimiter will always be ". However, values may contain ' characters, which would break your HTML. To keep it simple and not worry about what might or mightn't pose an issue, HTML-escape your values!
<section data-settings="<?= htmlspecialchars(json_encode($foo)); ?>"></section>
This is guaranteed to work, always, no matter what values you pipe in or how you encode them.
NOTE that htmlspecialchars will by default only encode ", not '; so you must use " as the delimiter in HTML (or change the default escaping behavior).
Double-quotes is just convention - standard in JSON in many languagues. So if you want to store JSON in HTML attribute with double-quotes. You can encode that
In PHP
$encoded_json = base64_encode(json_encode($var));
In HTML
<section id="settings" data-settings='<?=$encoded_json?>'>
In JS
var variable = JSON.parse(atob(encoded_json));

Remove multiple quotes in json encoded array

is it possible to strip double quotes from json encoded array?
Exaample:
{"96":{"term_id":96,"name":"AS Roma","slug":"as-roma","term_group":0,"term_taxonomy_id":100,"taxonomy":"klient","description":"HWDP","parent":0,"count":5,"object_id":1800,"filter":"raw"},"100":{"term_id":100,"name":"Atletico Madrid","slug":"atletico-madrid","term_group":0,"term_taxonomy_id":104,"taxonomy":"klient","description":""vamos amigos"","parent":0,"count":6,"object_id":1800,"filter":"raw"}}
This is an array of values from wordpress get_the_terms function. As you may see one of those values "description":""vamos amigos"" has doubled double quotes (the input text in description is inside quotes). Which gives me an error on ajax response. I've tried everything to strip this double quotes - nothing works for me?
I would appreciate any indications.

How to format result of array

How to format this result of array:
[{"name":"Pendapatan","y":"1464333560100.00"}]
in to this format:
[{name:'Pendapatan',y:1464333560100.00}]
i have try str replace but the result remove all string
[{name:Pendapatan,y:1464333560100.00}]
what should i do?
The only thing that would remotely make sense would be to change "1464333560100.00" to 1464333560100, i.e. change the string to a number. That's a valid change. To do that, you need to make your PHP value a number, not a string:
json_encode(['y' => '1464333560100.00']) → string
json_encode(['y' => 1464333560100.00]) → number
Do note that the result will be 1464333560100, without trailing .00. That's because those two numbers are equivalent; it's irrelevant how many trailing zeros you have, it doesn't change the value as such.
The rest of the formatting change is completely irrelevant. Whether you have single quotes or double quotes or no quotes does not change the data structure and its values at all. If your goal is to produce valid JSON, then the format as is (double quotes everywhere) is in fact necessary.
I got it wrong. You can use this;
json_encode(array('name' => 'Pendapatan', 'y' => 1464333560100.00));
Also you can do the test for json on this site http://jsoneditoronline.org/

Why does PHP require double quotes for key variable in adding array key-value pairs?

Why does PHP require double quotes for key variable in adding array key-value pairs?
foreach($coreXml->Environment as $Environment) {
$env = $Environment->Name;
$envArr["$env"] ="test";
}
In this loop, if I don't use double quotes around the $env or use single quotes, it will break the code with error "Illegal offset type". Any idea on why that is? thanks!
You do not require double quotes. $envArr[$env] is perfectly legal syntax.
$envArr['$env'] would create the literal key '$env', which is not what you want.
However, if $env is not a string or integer, but, say, an object or null, that's when you'd get an illegal offset notice. Interpolating the variable into a string with "$env" forces the variable to be cast to a string, which avoids that problem. But then arguably the problem is that you're trying to use a non-string as array offset, so an error message would be perfectly justified and preferable.
I'd be guessing that you're using SimpleXML and $env is a SimpleXMLElement object. You should be using this then:
$envArr[(string)$env]
// or
$envArr[$env->__toString()]
That's basically the same as encasing the variable in double quotes, it forces a string cast, but in this case it's explicit and not a mystery.
I'm guessing $env is null or an object. If null the case $envArr[""] would be the result of $envArr["$env"] It's perfectly fine to have an empty string index.
Check the manual for string interpolation rules. When you put variables inside of double quotes, their values will be interpolated. When you put variables inside of single quotes, they will not be interpolated. The following is literally trying to load the array at index '$env':
$envArray['$env']

Working with colons inside array keys, or how to avoid it

I am being passed an array by an identity management system (SAML2.0 based) which provides me a set of user attributes in an array.
The identity provider configures the structure of this data, and I am providing this (much larger company) with a service. Altering the way I receive this array is not in my control.
The array arrives with me in this form (this is what I see if I print_r the array):
Array
(
[http://longurl/surname] => Array ([0] => Smith)
[http://longurl/firstname] => Array ([0] => John)
);
As you can see, the keys to this array of arrays is a URL (I'm sure they have a good reason?!). However if I try to work with this array like so:
echo 'Hello Mr. '.$SAMLDATA[http://longurl/surname][0];
This is no good, because colons aren't valid characters inside variables (or so I read).
Escaping the character doesn't seem to work, any idea what I can do here? Many thanks.
Since PHP's non-integer array keys are strings, they must be quoted as strings. If you do not quote them, PHP will issue an E_NOTICE about undefined constants, assuming you meant to use a string in place of the constant, and if you attempt to use an array key with a colon like those URLs, it will likely result in a fatal syntax error.
So to fix your issue, you really only need to correctly quote the array keys as in:
echo 'Hello Mr. '.$SAMLDATA['http://longurl/surname'][0];
Note that the only circumstance in which it is acceptable not to quote string array keys is when interpolated inside a double-quote string. For example:
$str = "This double-quoted string has an $array[key] value inside it";
For simple array values like the above, you need not quote the key in a double-quoted string.
However, in your case, you will probably need to use the {} syntax to access one of these URL keys in an interpolated string. When using {} you will need to quote the string array keys. Generally I always recommend using the {} syntax for array and object values, as it improves readability:
// When using {} enclosures, you do need to quote the key
$str = "This double-quoted string has an {$array['key']} value inside it";
The various rules surrounding the above examples in double-quoted strings are documented here.

Categories