php object to json

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
and77
Forum Newbie
Posts: 8
Joined: Sun Nov 21, 2010 10:03 am

php object to json

Post by and77 »

Hi all,
I have done this program to build a json object from a php object but i have some errors when i process it from javascript.

Code: Select all

<?php
class Image{
	private $path;
	private $width;
	private $height;
	function __construct($path='',$width=0,$height=0){
		$this->path=$path;
		$this->width=$width;
		$this->height=$height;
	}
	function get_path(){
		return $this->path;
	}
	function get_width(){
		return $this->width;
	}
	function get_height(){
		return $this->height;
	}
	function set_path($path){
		$this->$path=$path;
	}
	function set_width($width){
		$this->$width=$width;
	}
	function set_height($height){
		$this->$height=$height;
	}
	public function encodeJSON()
	{
		foreach ($this as $key => $value)
		{
			$json->$key =$value;
		}
		return json_encode($json);
	}
	public function decodeJSON($json_str)
	{
		$json = json_decode($json_str, 1);
		foreach ($json as $key => $value)
		{
			$this->$key = $value;
		} 
	}
}


$dir="/home/and/Immagini/16_10_San_Michele/";
$images=array();
if( is_dir($dir)){//if $dir is a directory
	if( $dir_handle=opendir($dir) ){//open directory
		while( false !== ($file=readdir($dir_handle))){//read the directory
			if( is_dir($file)){//if the file is a directory
				continue;
			}
			else{//if is a file
				$path="$dir"."$file";
				//echo "PERCORSO ALL'IMMAGINE: ".$path."\n";
				list($width,$height)=getimagesize($path);
				$image = new Image($path,$width,$height);
				$images[]=$image;//array of Image objects
			}
		}
	}
}
$length=count($images);

for($i=0;$i<$length;$i++){//build json object
	$j_string=$images[$i]->encodeJSON();
	$json_string.="\"image".$i."\":";
	$json_string.=$j_string.",";
}
echo $json_string;

?>


output:

var images={"image266":{"path":"\/home\/and\/Immagini\/16_10_San_Michele\/IMG_0936.JPG","width":4752,"height":3168},
"image267":{"path":"\/home\/and\/Immagini\/16_10_San_Michele\/IMG_0832.JPG","width":2352,"height":1568},
"image268":{"path":"\/home\/and\/Immagini\/16_10_San_Michele\/IMG_0784.JPG","width":4752,"height":3168},
"image269":{"path":"\/home\/and\/Immagini\/16_10_San_Michele\/IMG_0756.JPG","width":4752,"height":3168},
"image270":{"path":"\/home\/and\/Immagini\/16_10_San_Michele\/IMG_0976.JPG","width":4752,"height":3168}
}
Can anyone explain me where is the problem?How can i build a json object from a php object?
maxx99
Forum Contributor
Posts: 142
Joined: Mon Nov 21, 2011 3:40 am

Re: php object to json

Post by maxx99 »

Use built-in JSON methods from PHP :)
http://php.net/manual/en/function.json-encode.php

Create your own array or e.g. cast your object to array :)
Post Reply