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.

Mohammad Aghayari
  • 1,010
  • 3
  • 15
  • 38
  • New lines like this is not valid json. If you want to preserve new lines you must escape them. see [documentation](http://www.yiiframework.com/doc-2.0/yii-helpers-basejson.html#encode()-detail) – chris--- Jan 13 '17 at 11:03
  • If you use PHP 5.0.2 or greater you can use `$str = str_replace(PHP_EOL, '', $str);` – Yosvel Quintero Jan 13 '17 at 11:08

1 Answers1

2

Remove new lines in $title->title

trim(preg_replace('/\s\s+/', '<br/>', $title->title ));