Magical PHP JSON Object Cleaner


I wrote this method the other day that takes a simple PHP object, inspects it’s properties and “prunes” empty ones. I wrote this method in order to compress JSON objects by removing null properties before sending them down the wire, a big problem when using base objects or models.

If you find this useful or a have a suggestion, feel free to let me know!

private function getStripped($obj) {
		$objVars = get_object_vars($obj);

		if(count($objVars) > 0) {
			foreach($objVars as $propName => $propVal) {
				if(gettype($propVal) == "object") {
					$cObj = $this->getStripped($propVal);
					if($cObj == null) {
						unset($obj->$propName);
					} else {
						$obj->$propName = $cObj;
					}
				} else {
					if(empty($propVal)) {
						unset($obj->$propName);
					}
				}
			}
		} else {
			return null;
		}
		return $obj;
	}

No related content found.

Leave a comment