how to encode an url to json using php - php

I want to throw an URL along with some text output as a json from my php webpage and for this I have used json_encode() function in php and the following is my php array that will be converted to json:
$output= array (
'payload' =>
array (
'google' =>
array (
'expectUserResponse' => true,
'richResponse' =>
array (
'items' =>
array (
0 =>
array (
'simpleResponse' =>
array (
'textToSpeech' => '<speak>some text... <audio src=\"https://example.com\"></audio></speak>',
'displayText' => 'some text...',
),
),
),
'suggestions' =>
array (
0 =>
array (
'title' => 'cancel',
),
),
),
),
),
);
echo json_encode($output);
and this php code produces the following json output:
{
"payload": {
"google": {
"expectUserResponse": true,
"richResponse": {
"items": [
{
"simpleResponse": {
"textToSpeech": "<speak>some text... <audio src=\\\"https://example.com\\\"></audio></speak>",
"displayText": "some text..."
}
}
],
"suggestions": [
{
"title": "cancel"
}
]
}
}
}
}
But I need the the following json output:
{
"payload": {
"google": {
"expectUserResponse": true,
"richResponse": {
"items": [
{
"simpleResponse": {
"textToSpeech": "<speak>some text... <audio src=\"https://example.com\"></audio></speak>",
"displayText": "some text..."
}
}
],
"suggestions": [
{
"title": "cancel"
}
]
}
}
}
}
I did not understand how to throw the URL in the json as per my requirment.

If you don't want the escaped slashes, you can use
json_encode($response, JSON_UNESCAPED_SLASHES);
to tell PHP not to escape these slashes.
But if you are talking about the backslashes, they have to be escaped like that since PHP interprets them as escape characters. You can always manually remove them on your receiving end.

'<speak>some text... <audio src=\"https://example.com\"></audio></speak>',
The double quotes do not need to be escaped here. The backslashes are treated literally because the string is single quoted. A backslash can only escape a single quote or another backslash inside of single quoted strings. Any other following character results in a literal backslash.
Either '<speak>some text... <audio src="https://example.com"></audio></speak>' (no escaping) or
"<speak>some text... <audio src=\"https://example.com\"></audio></speak>" (double quotes) should give the output you want.

Related

Fix invalid JSON [duplicate]

This question already has answers here:
How can I parse a JSON string in which objects are not comma separated?
(5 answers)
Closed 4 years ago.
I have a huge file that unfortunately contains invalid JSON.
It looks like list of arrays, not separated with a comma:
[{
"key": "value"
}]
[
[{
"key": "value",
"obj": {}
},
{}
]
]
[{
"key": "value",
"obj": {}
}]
The content inside every square brackets pair seems to be a valid JSON by itself.
The question is how to fix this JSON quickly with "search and replace"? (or any other method)
Tried many combinations including replacing "][" to "],[" and wrapping the whole file with one more square brackets pair making it array of arrays.
Every time it gives me invalid JSON.
Please help.
You can replace the closing brackets with '],' and wrap the entire string in brackets.
This snippet illustrates the method with the supplied sample data by applying the algorithm and then calling eval on the resulting string.
let jsonString = `[{
"key": "value"
}]
[
[{
"key": "value",
"obj": {}
},
{}
]
]
[{
"key": "value",
"obj": {}
}]`;
jsonString = jsonString.replace( /]/g, '],' );
jsonString = '[' + jsonString + ']';
myObject = eval( jsonString );
console.log( typeof myObject);
console.log( myObject.length );
console.log( myObject );
This is a dynamic php solution, but I would cringe to have to use this as a reliable source of data. This is a bandaid. Whatever code is producing this invalid json NEEDS to be fixed asap.
My regex pattern will seek all occurrences of ], zero or more spaces, then ] then it will add a comma after the ].
The entire string is wrapped in square brackets to make the json string valid.
The risk may or may not be obvious to all -- if any of the actual keys or values contain strings that qualify for replacement, then they will be damaged. This is why using regex on json is not recommended.
Code: (Demo)
$bad_json = '[{
"key": "value"
}]
[
[{
"key": "value",
"obj": {}
},
{}
]
]
[{
"key": "value",
"obj": {}
}]';
$valid_json = "[" . preg_replace("~]\K(?=\s*\[)~", ",", $bad_json) . "]";
var_export(json_decode($valid_json, true));
Output:
array (
0 =>
array (
0 =>
array (
'key' => 'value',
),
),
1 =>
array (
0 =>
array (
0 =>
array (
'key' => 'value',
'obj' =>
array (
),
),
1 =>
array (
),
),
),
2 =>
array (
0 =>
array (
'key' => 'value',
'obj' =>
array (
),
),
),
)

Some data lost when decode JSON to PHP array

I can decode JSON in PHP To array But some data that have in JSON disappear when decode to array.
This is my JSON file
[
{
"name": "Games1",
"price": "€ 25.53",
"platform": "<span class=\"platform battle-net\"></span>",
"region": "GLOBAL",
"url": "localhost"
},
{
"name": "Games2",
"price": "€ 24.99",
"platform": "<span class=\"platform xbox-live\"></span>",
"region": "GLOBAL",
"url": "localhost"
}
]
This is my php code
$data = file_get_contents("game.json");
for ($i = 0; $i <= 31; ++$i) {
$data = str_replace(chr($i), "", $data);
}
$data = str_replace(chr(127), "", $data);
if (0 === strpos(bin2hex($data), 'efbbbf')) {
$data = substr($data, 3);
}
$data = json_decode($data,true);
print_r($data);
My result from print_r($data);
Array ( [0] => Array ( [name] => Games1 [price] => € 25.53 [platform] => [region] => GLOBAL [url] => localhost )
[1] => Array ( [name] => Games2 [price] => € 24.99 [platform] => [region] => GLOBAL [url] => localhost ) )
My value in Platform is disappear. Can anyone know What is the problem?
Your JSON contains HTML tags, and these are being interpreted by the browser when it shows the result of print_r(). Use the browser's View Source command to see the raw output and you should see the spans.
You can also use htmlentities() to convert them to escaped characters, which will be shown as is by the browser.
$output = print_r($data, true);
echo "<pre>" . htmlentities($output, ENT_COMPAT) . "</pre>";
Using <pre> will maintain the formatting as well.
In order to keep HTML inside of JSON, you have to follow multiple rules:
Escape quotation marks
<span class=\"class-name\"><\/span>
Escape the forward slash in closing tags <\/span>
In self closing tags, leave a space between slash and closing bracket.
<img ... />
Make sure to encode special character entities like this:
€
Additionally, you can avoid duplicating your
<span> tags, and just store their class name like this: "platform": "battle-net", or "platform": "xbox-live",.

Generate php array definition from JSON

My question is a bit different to most like this, I basically want to do the opposite to this question from Haluk.
So I have a JSON string:
{
"main":
{
"title": "QuickPub",
"defaultRole": "BU"
},
"roles":
{
"TU":
{
"name": "testUser",
"code": "TU"
}
}
}
and I want to be able to generate a string containing a php array definition from it:
<?php
return [
"main" =>
[
"title" => "QuickPub",
"defaultRole" => "BU"
],
"roles" =>
[
"TU" =>
[
"name" => "testUser",
"code" => "TU"
]
]
];
?>
EDIT:
I have tried json_decode() but this produces a variable, I need a string that I can put in a php file that will reproduce this without using php_decode.
I think this will solve your problem. First of all convert your json string to an array using json_decode($string,1); then convert that array to string representation using print_r($array,1); this will return your result as array string representation.
For example:
$json='{}' // its a demo
$array= json_decode($json,1); // an array
$result = print_r($array,1);
echo $result;
This is an adaptation of Being Sunny's answer, but using the var_export() function rather than print_r.
As described here by phihad
var_export prints valid php code. Useful if you calculated some values and want the results as a constant in another script
the script:
$json = '{"main":{"title": "QuickPub","defaultRole": "BU"},"roles":{"TU":{"name": "testUser","code": "TU"}}}';
$array = json_decode($json, 1);
$result = var_export($array, 1);
echo $result;
produces:
array(
'main' => array(
'title' => 'QuickPub',
'defaultRole' => 'BU',
),
'roles' => array(
'TU' => array(
'name' => 'testUser',
'code' => 'TU',
),
),
)
This can be achieved using this code:
$output = 'return ' . rtrim(preg_replace(['/{/', '/}/', '/:/'], ['[', ']', ' =>'], $json)) . ';';
this replaces { with [, } with ], and : with =>, trims any whitespace from the end, appends a ; and prepends a return statement.
this produces the output requested in the question bar the open and closing php tags.

Creat json data file for gallery file with php

I know this question was asked already for couple times, I've seen the answers but it already helped me a lot, but i need to solve one more problem regarding to this.
So the question is:
I need to build json file with php.
Here how looks my json file that i need:
{
"fashion":[
{
"alt":"Alisa",
"src":"img/fashion/Alisa/kubik.jpg",
"class":"albumItem",
"id":"FashionAlbum001",
"itemNum":0,
"album":[
{
"alt":"albumImg1",
"src":"img/fashion/Alisa/alisa1.jpg"
},
{
"alt":"albumImg1",
"src":"img/fashion/Alisa/alisa5.jpg"
},
{
"alt":"albumImg1",
"src":"img/fashion/Alisa/alisa7.jpg"
}
]
},
{
"alt":"2-Addis",
"src":"img/fashion/2-Addis/kubik.jpg",
"class":"albumItem",
"id":"FashionAlbum002",
"itemNum":1,
"album":[
{
"alt":"albumImg1",
"src":"img/fashion/2-Addis/addis1.jpg"
},
{
"alt":"albumImg4",
"src":"img/fashion/2-Addis/addis4.jpg"
}] } ] }
and so on...
I can't find out how to make a list of images inside each album
This is a php function a have
function buildJson(){
$json = json_encode(array(
"Fashion" => array(
"alt" => "Alisa",
"src" => "img/fashion/Alisa/kubik.jpg",
"id" => "FashionAlbum001",
"itemNum"=>"1",
"album"=>array(
"src"=>"img/fashion/Alisa/alisa1.jpg",
),
array(
"src"=>"img/fashion/Alisa/alisa5.jpg",
),
array(
"src"=>"img/fashion/Alisa/alisa7.jpg",
),
)
));
echo $json;
}
but I get json like this one:
{
"Fashion": {
"0": {
"src": "img/fashion/Alisa/alisa2.jpg"
},
"1": {
"src": "img/fashion/Alisa/alisa3.jpg"
},
"alt": "Alisa",
"src": "img/fashion/Alisa/kubik.jpg",
"id": "FashionAlbum001",
"itemNum": "0",
"album": {
"src": "img/fashion/Alisa/alisa1.jpg"
}
}
}
How is it possible to fix it?
Thank you!
Please pay more attention to the code you're writing :) Try to decode correct version of your json file and compare it to one you wrote. You should see some differences.
Your problem ir what follows after album key. You are assigning array with only one value to it instead of assigning array of arrays.
This is the way to go:
"album" => array(
array("src" => "img/fashion/Alisa/alisa1.jpg"),
array("src" => "img/fashion/Alisa/alisa5.jpg"),
array("src" => "img/fashion/Alisa/alisa7.jpg"),
),
you trouble in nesting album array
fixed code
function buildJson(){
$json = json_encode(
array(
"Fashion" => array(
"alt" => "Alisa",
"src" => "img/fashion/Alisa/kubik.jpg",
"id" => "FashionAlbum001",
"itemNum"=>"1",
// nesting error here
"album"=> array(
array("src"=>"img/fashion/Alisa/alisa1.jpg"),
array("src"=>"img/fashion/Alisa/alisa5.jpg"),
array("src"=>"img/fashion/Alisa/alisa7.jpg")
)
)
)
);
echo $json;
}

PHP json_encode() results showing JSONLint errors

I am having issues with validating the output of my json_encode() function.
I am pulling in an XML feed with cURL, converting it into an array, and converting that array into JSON with json_endode(). Ill spare you the cURL stuff:
foreach ($xmlObjects->articleResult as $articleResult) {
$article = array(
"articleResult" =>
array(
'articleId' => (string)$articleResult->articleId,
'title' => (string)$articleResult->title,
'subhead' => (string)$articleResult->subhead,
'tweet' => (string)$articleResult->tweet,
'publishedDate' => (string)$articleResult->publishedDate,
'image' => (string)$articleResult->image
),
);
$json = str_replace('\/','/',json_encode($article));
echo $json;
}
Which is giving me a JSON readout of:
{
"articleResult": {
"articleId": "0001",
"title": "Some title",
"subhead": "Some engaging subhead",
"tweet": "Check out this tweet",
"publishedDate": "January 1st, 1970",
"image": "http://www.domain.com/some_image.jpg"
}
}
{
"articleResult": {
"articleId": "0002",
"title": "Some title",
"subhead": "Some engaging subhead",
"tweet": "Check out this tweet",
"publishedDate": "January 1st, 1970",
"image": "http://www.domain.com/some_image.jpg"
}
}
This will give me a JSONLint error saying:
Parse error on line 10:
..._120x80.jpg" }}{ "articleResult
---------------------^
Expecting 'EOF', '}', ',', ']'
So naturally I will add in the comma, which gives me an End of File expectation:
Parse error on line 10:
..._120x80.jpg" }},{ "articleResu
---------------------^
Expecting 'EOF'
I am new to JSON, but I have checked the website and a few resources for proper JSON formatting and structure, and from what I can see my readout is following the guidelines. Any pointers?
Resources I've checked:
JSON.org naturally
Wikipedia has well documented page
W3Resource Had a good explanation of structure.
JSONLint
You were encoding 2+ objects into json string, you need [ ] to wrap them
the correct syntax is
[
{ /* first object */ }
, { /* second object */ }
, { /* third object */ }
]
the things you need to look out are
[ ] wrap
separate objects by comma
Solution
$json = array();
foreach ($xmlObjects->articleResult as $articleResult) {
$article = array(
"articleResult" =>
array(
'articleId' => (string)$articleResult->articleId,
'title' => (string)$articleResult->title,
'subhead' => (string)$articleResult->subhead,
'tweet' => (string)$articleResult->tweet,
'publishedDate' => (string)$articleResult->publishedDate,
'image' => (string)$articleResult->image
),
);
$json[] = $article;
}
echo json_encode($json);

Categories