<?php
$printer = new XMLPrinter('$data',array('path','value'));
$printer->write('111222222 ');
class XMLPrinter{
public $columns = array();
public $onlyFirstElement = false;
public $rootName = '$root';
public function __construct($rootName='$root',$columns=array('type','path','value'),$onlyFirstElement=false){
$this->rootName = $rootName;
$this->columns = $columns;
$this->onlyFirstElement = $onlyFirstElement;
}
public function write($data){
if (!$data instanceof SimpleXMLElement)
$data = simplexml_load_string($data);
$this->writeHeader();
$this->_write($data,$this->rootName,0);
$this->writeFooter();
}
public function _write(SimpleXMLElement $data,$name){
$children = array();
foreach($data as $item)
$children[] = $item->getName();
$children = array_unique($children);
foreach($children as $child){
$item = $data->$child;
$isArray = isset($item[1]);
$i = -1;
while(isset($item[++$i])){
$arrayPat = $isArray ? "[$i]" : '';
$elementPat = $name.'->'.$item[$i]->getName().$arrayPat;
if (count($item[$i]->attributes())>0)
foreach($item[$i]->attributes() as $attr=>$value)
$this->writeRow('attribute', $elementPat."['$attr']", $value);
if (count($item[$i]->children())>0)
$this->_write($item[$i]->children(),$elementPat);
else
$this->writeRow('element', $elementPat, $item[$i]);
if ($this->onlyFirstElement)
break;
}
}
}
public function writeHeader(){
echo '<style>';
echo "nobr{max-width:600px;overflow:hidden;display:block;}";
echo '</style>';
echo '<table border="0" cellspacing="0"><tr>';
foreach($this->columns as $column)
echo '<th>'.$column.'</th>';
echo '</tr>';
}
public function writeRow($type,$path,$value){
if (strlen(trim($value)) > 0){
echo '<tr>';
foreach($this->columns as $column)
echo '<td><nobr>'.htmlspecialchars($$column).'</nobr></td>';
//echo '<td><nobr>echo \'<br>'.str_replace("'",'\\\'',htmlspecialchars($$column)).'=\','.htmlspecialchars($$column).';</nobr></td>';
echo '</tr>';
}
}
public function writeFooter(){
echo "</table>";
}
}
วันเสาร์ที่ 2 มีนาคม พ.ศ. 2556
XML Printer Class
ป้ายกำกับ:
php,
simplexmlelement,
xml display,
xml recursive
สมัครสมาชิก:
ส่งความคิดเห็น (Atom)
ไม่มีความคิดเห็น:
แสดงความคิดเห็น