为什么JSON_DECODE不能在这里工作?

时间:2016-02-07 14:34:58

标签: php json

这是我的代码

<?php
//json reader and writer for events Title,description,image,id  
// contact_details
class ffile {

    var $file_name = null;
    var $file_content;

    function __construct($name)
    {
        $this->file_name = $name;

        $this->file_content = file_get_contents($this->file_name);
        echo "size: " . filesize($this->file_name) . "<br/> Content" . $this->file_content . "<br/><br/><br/>";
    }

    function file_clear()
    {
        file_put_contents($this->file_name, '');
    }

    function write($str)
    {
        echo '<br/> Writing' . $str . '<br/>';
        file_put_contents($this->file_name, $str);
    }

    function get_data()
    {
        return $this->file_content;
    }

}

class CreateEvent {

    var $id;
    var $title;
    var $description;
    var $image;
    var $contact_name;
    var $contact_number;
    var $email;
    var $date;
    var $file_name;
    var $jsonStr;
    var $jsonArr;

    function getId()
    {
        //will implement it later       
        return 3;
    }

    function __construct($filename, $title, $desc, $image, $cname, $cnumber, $email, $date)
    {
        $this->id = $this->getId() + 1;
        $this->title = $title;
        $this->description = $desc;
        $this->image = $image;
        $this->contact_name = $cname;
        $this->contact_number = $cnumber;
        $this->email = $email;
        $this->date = $date;
        $this->file_name = $filename;

        $jsonArr = array($this->id => array(
                'title' => $this->title,
                'description' => $this->description,
                'image' => $this->image,
                'contact-name' => $this->contact_name,
                'contact-number' => $this->contact_number,
                'email' => $this->email,
                'date' => $this->date
            )
        );

        $this->jsonStr = json_encode($jsonArr, JSON_UNESCAPED_UNICODE);
    }

    function write()
    {
        $ab = new ffile($this->file_name);
        $nnew = $this->jsonStr;

        if (filesize($this->file_name) != 0) {
            $jjdata = $ab->get_data();
            echo "<br/>Contents " . $jjdata . "This was data <br/> <br/>";
            $old = json_decode(html_entity_decode(stripslashes(($jjdata))));
            echo '<br/>Decoded string: ' . print_r($old) . '<br/>' . json_last_error() . '<br/>';

            echo "<br/>Json DEcoded" . var_dump($old) . "This was decoded json data <br/>Json str:" . $this->jsonStr . '<br/>';
            $nnew = array_push($old, $this->jsonArr);
            echo "<br/>Raw array " . print_r($nnew) . "<br/>";
        }

        $ab->write($nnew);
    }

}

$jso = new CreateEvent("aka.json", "ttile", "description", "image", "contactname", "contactnumber", "email", "date");
$jso->write();

问题出现在CreateEvent类的write函数中。当我第二次运行代码时(记得弄清楚发生了什么,你必须运行它两次)json_decode正在做一些我无法弄清楚的事情< / p>

我正在运行php:PHP 5.5.9-1ubuntu4.14(cli)(建于:2015年10月28日01:34:46)

1 个答案:

答案 0 :(得分:0)

要求:将新的detail记录附加到包含PHP数组details作为JSON文本的文件中。

每个详细记录都是一个PHP数组。

代码:

//json reader and writer for events Title,description,image,id  
// contact_details
class ffile {

    public $file_name = null;
    public $file_content = null;

    function __construct($name)
    {
        $this->file_name = $name;

        if (file_exists($this->file_name)) {
            $this->file_content = file_get_contents($this->file_name);
        }
    }

    function file_clear()
    {
        file_put_contents($this->file_name, null);
    }

    function write($str)
    {
        file_put_contents($this->file_name, $str);
    }

    function get_data()
    {
        return $this->file_content;
    }
}

class CreateEvent {

    public $id;
    public $title;
    public $description;
    public $image;
    public $contact_name;
    public $contact_number;
    public $email;
    public $date;

    /**
     * file to store the JSON string in
     * @var string 
     */
    public $file_name;

    /**
     * The imput details as a PHP array
     * @var array 
     */
    public $phpArr;

    /**
     * The input detail array (phpArray) as a JSON encodd string
     * @var string
     */   
    public $jsonStr;


    function getId()
    {
        //will implement it later       
        return 3;
    }

    /**
     * Convert the input details to a PHP array
     * then convert the array to a JSON string 
     * 
     * @param type $filename
     * @param type $title
     * @param type $desc
     * @param type $image
     * @param type $cname
     * @param type $cnumber
     * @param type $email
     * @param type $date
     */
    function __construct($filename, $title, $desc, $image, $cname, $cnumber, $email, $date)
    {
        $this->id = $this->getId() + 1;
        $this->title = $title;
        $this->description = $desc;
        $this->image = $image;
        $this->contact_name = $cname;
        $this->contact_number = $cnumber;
        $this->email = $email;
        $this->date = $date;
        $this->file_name = $filename;

        $this->phpArr = array($this->id => array(
                'title' => $this->title,
                'description' => $this->description,
                'image' => $this->image,
                'contact-name' => $this->contact_name,
                'contact-number' => $this->contact_number,
                'email' => $this->email,
                'date' => $this->date
            )
        );

        $this->jsonStr = json_encode($this->phpArr, JSON_UNESCAPED_UNICODE);
    }

    /**
     * Append the new detail to the existing file.
     * 
     * Method:
     *   1) Load old file and convert to a PHP array
     *   2) Append the new detail to the array
     *   3) Convert back to JSON and write to the file
     * 
     * @throws \InvalidArgumentException
     */
    function write()
    {
        $ab = new ffile($this->file_name);

        if (strlen($this->jsonStr) != 0) {
            $oldJsonStr = $ab->get_data();

            $oldArray = array(); // alway provide an array...
            if (strlen($oldJsonStr) > 0) { 
                $oldArray = json_decode($oldJsonStr, true); // force array
            }

            if (is_array($oldArray)) { // valid array
                $newCount = array_push($oldArray, $this->phpArr); // this does not return an array
                $newJsonStr = json_encode($oldArray, JSON_UNESCAPED_UNICODE);

                $ab->write($newJsonStr);
            }
        }
        else {
            throw new \InvalidArgumentException('file: '. $this->file_name .', Not a valid JSON array.');
        }
    }
}

运行它:

// write one new record
$recNo = rand(100, 999);
$jso = new CreateEvent("aka.json", "ttile" .'-'. $recNo, 
                                    "description" .'-'. $recNo, 
                                    "image", "contactname", "contactnumber", "rfv@here.com", date('Y-m-d H:i:s'));

$jso->write();

// display file contents as PHP 
$ffile = new ffile($jso->file_name); 
$fileArray = json_decode($ffile->get_data(), true);                  

echo '<br /><pre>', PHP_EOL;
print_r($fileArray);
echo '</pre><br />', PHP_EOL;

/* clear file * / $ffile = new ffile($jso->file_name); 
                  $ffile->file_clear(); /**/

重复运行的样本输出

Array
(
    [0] => Array
        (
            [4] => Array
                (
                    [title] => ttile-232
                    [description] => description-232
                    [image] => image
                    [contact-name] => contactname
                    [contact-number] => contactnumber
                    [email] => rfv@here.com
                    [date] => 2016-02-07 21:08:41
                )

        )

    [1] => Array
        (
            [4] => Array
                (
                    [title] => ttile-809
                    [description] => description-809
                    [image] => image
                    [contact-name] => contactname
                    [contact-number] => contactnumber
                    [email] => rfv@here.com
                    [date] => 2016-02-07 21:08:44
                )

        )

    [2] => Array
        (
            [4] => Array
                (
                    [title] => ttile-800
                    [description] => description-800
                    [image] => image
                    [contact-name] => contactname
                    [contact-number] => contactnumber
                    [email] => rfv@here.com
                    [date] => 2016-02-07 21:08:51
                )
        )
)
相关问题