Skip to content

Instantly share code, notes, and snippets.

@evanmcd
Created July 10, 2012 03:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save evanmcd/3080802 to your computer and use it in GitHub Desktop.
Save evanmcd/3080802 to your computer and use it in GitHub Desktop.
First try at a ProcessWire module to convert a PageArray to JSON
<?php
/**
* ProcessWire PagesToJSON Module
*
* Adds the ability to output a PageArray as JSON
* Original code from RC here: http://processwire.com/talk/topic/1417-export-array-to-json-format/
* Don't for get to add header("Content-type: application/json"); to pages that output JSON only
*
* ProcessWire 2.x
* Copyright (C) 2011 by Ryan Cramer
* Licensed under GNU/GPL v2, see LICENSE.TXT
*
* http://www.processwire.com
* http://www.ryancramer.com
*
*/
class PagesToJSON extends WireData implements Module {
public static function getModuleInfo() {
return array(
'title' => __('Pages to JSON', __FILE__), // Module Title
'summary' => __('Adds the ability to output a PageArray as JSON.', __FILE__), // Module Summary
'version' => 101,
'permanent' => true,
'singular' => true,
'autoload' => true,
);
}
protected $config;
/**
* Initialize the hooks
*
*/
public function init() {
$this->config = $this->fuel('config');
$this->addHook('Pages::toJSON', $this, 'pagesToJSON');
}
/**
* Return a string with all of the Page data in the PageArray encoded as JSON
*
*
* @return string JSON formatted data
*
*/
public function pagesToJSON($event) {
$pages = $event->object;
$a = array();
foreach($pages as $page) {
$a[] = pageToArray($page);
}
$event->return = json_encode($a);
}
/**
* Return an array with the standard PW fields and a nested data array of all custom Page template fields
*
*
* @return array the Page object as an array
*
*/
protected function pageToArray(Page $page) {
$outputFormatting = $page->outputFormatting;
$page->setOutputFormatting(false);
$data = array(
'id' => $page->id,
'parent_id' => $page->parent_id,
'templates_id' => $page->templates_id,
'name' => $page->name,
'status' => $page->status,
'sort' => $page->sort,
'sortfield' => $page->sortfield,
'numChildren' => $page->numChildren,
'template' => $page->template->name,
'parent' => $page->parent->path,
'data' => array(),
);
foreach($page->template->fieldgroup as $field) {
if($field->type instanceof FieldtypeFieldsetOpen) continue;
$value = $page->get($field->name);
$data['data'][$field->name] = $field->type->sleepValue($page, $field, $value);
}
$page->setOutputFormatting($outputFormatting);
return $data;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment