0

I need to write the following output in PHP:

var data = { "count": 1, "elements": [{"id": 1, "title": "title123", "url": "x123.php", "file_url": "x124.jpg"}]}

I have tried:

$txt = 'var data = { "count": 1,"elements": ';
$txt = $txt + '[{"id": 1, "title": "title123", "url": "x123.php", "file_url": "x124.jpg"}';
    $something = json_encode($txt);
    echo $something;
    //
    $something = print_r($txt);
    echo $something;
    //
    $something = print_r(json_decode($txt));
    echo $something;
    //
    ob_start;
    var_dump($txt);
    $something = ob_get_contents();
    ob_end_clean();
    echo $something;

I also have tried this:

$txt = '?var ?data ?= { "count": 1,"elements":';
for ($x = 0; $x <= strlen($txt); $x++) {
    $neso = substr($txt,$x,1);
    if ($neso != "?") {
    echo "+" + $neso + "+" + $x;
    }
} 

Unfortunately I can not get any solution. All I get is 0 (zero) or 1 (one).

How can I get this output?

2 Answers 2

4

That's not how you generate json. PHP has absolutely NO clue what Javascript is - it's just plain text as far as PHP is concerned. When you do your $txt = 'var...', and encode that, you're producing a json representation of the STRING you produced in php, which means your json will become

"var data = {\"count\": etc...}"

and now the JSON you ALREADY had in there is escaped, and no longer json - it's just a plaintext string.

What you want is something more like:

$php_array = array(
   'count' => 1,
   'elements' => array(
       array('id' => 1, 'title' => etc...)
   )
)

$javascript = 'var txt = ' . json_encode($php_array) . ';';

Note that your echo "+" + $neso + "+" + $x; is utterly useless. + in PHP does mathematical addition. You're trying to do string concatenation, for which the operator is ..

Sign up to request clarification or add additional context in comments.

1 Comment

Welcome and, Well i must say thanks to you for your service on SO sir. @MarcB
2

Learn about the structure of arrays, objects, and how the same thing is written in JSON.

To create a real json with PHP, the best way would be the following:

  • create an array with the actual data
  • json encode it
  • pass it on

What will then be "echoed" if you try, will be the contents inside the first {}.

I would start by doing:

$data = array(
'count' => 1,
'elements' => array(
            'id' => 1,
            'title' => 'title123',
            'url' => 'x123.php',
            'file_url' => 'x124.jpg',
            ),
);

then: echo json_encode($data); or return $json_encode($data), to pass the data on.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.