0

I converted array to json to use data. I got error when there is break line in array.

Here is my code:

 <script>
        function showKnowledgeItem(id) {

            var title = [];
            var text = [];

    <?php
    $query = (new \yii\db\Query())
            ->select('')
            ->from('fc_knowledge')
            ->all();

    $arr = array();
    $arr = json_encode($query, true);
    $json_output = json_decode($arr);

    foreach ($json_output as $title) {
        ?>
                title [<?= $title->id ?>] = ["<?= $title->title ?>"];
        <?php
    }
    foreach ($json_output as $content) {
        ?>
                text [<?= $content->id ?>] = ["<?= $content->content ?>"];
        <?php
    }
    ?>
        }
    </script> 

This code works well. But when there is new line or break line in the array, it does not work.

The error obvious in this picture: enter image description here

Does anyone knows what I have to solve this problem. Tank you so much.

2
  • New lines like this is not valid json. If you want to preserve new lines you must escape them. see documentation Commented Jan 13, 2017 at 11:03
  • If you use PHP 5.0.2 or greater you can use $str = str_replace(PHP_EOL, '', $str); Commented Jan 13, 2017 at 11:08

1 Answer 1

2

Remove new lines in $title->title

trim(preg_replace('/\s\s+/', '<br/>', $title->title ));
Sign up to request clarification or add additional context in comments.

3 Comments

Malyaita But I need new line.
Does it removes all break in text?
Yes, then you need to replace new line to <br/>. I changed the code

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.