How to get html of a cell using PHPExcel? - php

I've tried to import an xlsx file to array, but noticed, that it contains simple text whereas if I open it in OpenOffice, I can see some words in the cell are bold.
#items: array:2 [
"url" => "theurl"
"meta_title" => "text with one bold word"
]
Is there a way to get somehow text with <b>one</b> bold word?
PHPExcel wiki says nothing about it. Its valueBinder applies only to csv and html files.

Thanks to Mark Baker. The HTML Writer code helps to create simple converter. Usage:
$richtextService = new RichTextService();
$value = $reader->getActiveSheet()->getCell('F2')->getValue();
$html = $richtextService->getHTML($value); // html in it
And the class:
namespace App\Services;
use PHPExcel_RichText;
use PHPExcel_RichText_Run;
use PHPExcel_Style_Font;
class RichTextService{
/**
* Takes array where of CSS properties / values and converts to CSS stri$
*
* #param array
* #return string
*/
private function assembleCSS($pValue = array())
{
$pairs = array();
foreach ($pValue as $property => $value) {
$pairs[] = $property . ':' . $value;
}
$string = implode('; ', $pairs);
return $string;
}
/**
* Create CSS style (PHPExcel_Style_Font)
*
* #param PHPExcel_Style_Font $pStyle PHPExcel_Style_Font
* #return array
*/
private function createCSSStyleFont(PHPExcel_Style_Font $pStyle)
{
// Construct CSS
$css = array();
// Create CSS
if ($pStyle->getBold()) {
$css['font-weight'] = 'bold';
}
if ($pStyle->getUnderline() != PHPExcel_Style_Font::UNDERLINE_NONE && $pStyle->getStrikethrough()) {
$css['text-decoration'] = 'underline line-through';
} elseif ($pStyle->getUnderline() != PHPExcel_Style_Font::UNDERLINE_NONE) {
$css['text-decoration'] = 'underline';
} elseif ($pStyle->getStrikethrough()) {
$css['text-decoration'] = 'line-through';
}
if ($pStyle->getItalic()) {
$css['font-style'] = 'italic';
}
$css['color'] = '#' . $pStyle->getColor()->getRGB();
$css['font-family'] = '\'' . $pStyle->getName() . '\'';
$css['font-size'] = $pStyle->getSize() . 'pt';
return $css;
}
/**
*
* #param PHPExcel_RichText|string $value
* #return string
*/
public function getHTML($value) {
if(is_string($value)) {
return $value;
}
$cellData = '';
if ($value instanceof PHPExcel_RichText) {
// Loop through rich text elements
$elements = $value->getRichTextElements();
foreach ($elements as $element) {
// Rich text start?
if ($element instanceof PHPExcel_RichText_Run) {
$cellData .= '<span style="' . $this->assembleCSS($this->createCSSStyleFont($element->getFont())) . '">';
if ($element->getFont()->getSuperScript()) {
$cellData .= '<sup>';
} elseif ($element->getFont()->getSubScript()) {
$cellData .= '<sub>';
}
}
// Convert UTF8 data to PCDATA
$cellText = $element->getText();
$cellData .= htmlspecialchars($cellText);
if ($element instanceof PHPExcel_RichText_Run) {
if ($element->getFont()->getSuperScript()) {
$cellData .= '</sup>';
} elseif ($element->getFont()->getSubScript()) {
$cellData .= '</sub>';
}
$cellData .= '</span>';
}
}
}
return str_replace("\n", "<br>\n", $cellData);
}
}

With this small adaptions this solution works with the successor PhpSpreadsheet:
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\RichText;
use PhpOffice\PhpSpreadsheet\RichText\Run;
use PhpOffice\PhpSpreadsheet\Style\Font;
class RichTextService {
/**
* Takes array where of CSS properties / values and converts to CSS stri$
*
* #param array
* #return string
*/
private function assembleCSS($pValue = array())
{
$pairs = array();
foreach ($pValue as $property => $value) {
$pairs[] = $property . ':' . $value;
}
$string = implode('; ', $pairs);
return $string;
}
/**
* Create CSS style (Font)
*
* #param Font $pStyle Font
* #return array
*/
private function createCSSStyleFont(Font $pStyle)
{
// Construct CSS
$css = array();
// Create CSS
if ($pStyle->getBold()) {
$css['font-weight'] = 'bold';
}
if ($pStyle->getUnderline() != Font::UNDERLINE_NONE && $pStyle->getStrikethrough()) {
$css['text-decoration'] = 'underline line-through';
} elseif ($pStyle->getUnderline() != Font::UNDERLINE_NONE) {
$css['text-decoration'] = 'underline';
} elseif ($pStyle->getStrikethrough()) {
$css['text-decoration'] = 'line-through';
}
if ($pStyle->getItalic()) {
$css['font-style'] = 'italic';
}
$css['color'] = '#' . $pStyle->getColor()->getRGB();
$css['font-family'] = '\'' . $pStyle->getName() . '\'';
$css['font-size'] = $pStyle->getSize() . 'pt';
return $css;
}
/**
*
* #param RichText|string $value
* #return string
*/
public function getHTML($value) {
if(is_string($value)) {
return $value;
}
$cellData = '';
if ($value instanceof PhpOffice\PhpSpreadsheet\RichText\RichText) {
// Loop through rich text elements
$elements = $value->getRichTextElements();
foreach ($elements as $element) {
// Rich text start?
print_r($element);
if ($element instanceof PhpOffice\PhpSpreadsheet\RichText\Run) {
$cellData .= '<span style="' . $this->assembleCSS($this->createCSSStyleFont($element->getFont())) . '">';
if ($element->getFont()->getSuperScript()) {
$cellData .= '<sup>';
} elseif ($element->getFont()->getSubScript()) {
$cellData .= '<sub>';
}
}
// Convert UTF8 data to PCDATA
$cellText = $element->getText();
$cellData .= htmlspecialchars($cellText);
if ($element instanceof PhpOffice\PhpSpreadsheet\RichText\Run) {
if ($element->getFont()->getSuperScript()) {
$cellData .= '</sup>';
} elseif ($element->getFont()->getSubScript()) {
$cellData .= '</sub>';
}
$cellData .= '</span>';
}
}
}
return str_replace("\n", "<br>\n", $cellData);
}
}

Related

PHP retrieve footnotes of pages on DOCX

i'm trying to convert DOCX to html, after search on google i can find this simple library as this convertor from https://github.com/xylude/Docx-to-HTML/blob/master/docx_reader.php , but that couldn't detect footnote on pages and i'm trying to add that to this library,
how can i detect styled text or simple text is/are footnote? that have special style?
<?php
class Docx_reader {
private $fileData = false;
private $errors = array();
private $styles = array();
public function __construct() {
}
private function load($file) {
if (file_exists($file)) {
$zip = new ZipArchive();
$openedZip = $zip->open($file);
if ($openedZip === true) {
//attempt to load styles:
if (($styleIndex = $zip->locateName('word/styles.xml')) !== false) {
$stylesXml = $zip->getFromIndex($styleIndex);
$xml = simplexml_load_string($stylesXml);
$namespaces = $xml->getNamespaces(true);
$children = $xml->children($namespaces['w']);
foreach ($children->style as $s) {
$attr = $s->attributes('w', true);
if (isset($attr['styleId'])) {
$tags = array();
$attrs = array();
foreach (get_object_vars($s->rPr) as $tag => $style) {
$att = $style->attributes('w', true);
switch ($tag) {
case "b":
$tags[] = 'strong';
break;
case "i":
$tags[] = 'em';
break;
case "color":
//echo (String) $att['val'];
$attrs[] = 'color:#' . $att['val'];
break;
case "sz":
$attrs[] = 'font-size:' . $att['val'] . 'px';
break;
}
}
$styles[(String)$attr['styleId']] = array('tags' => $tags, 'attrs' => $attrs);
}
}
$this->styles = $styles;
}
if (($index = $zip->locateName('word/document.xml')) !== false) {
// If found, read it to the string
$data = $zip->getFromIndex($index);
// Close archive file
$zip->close();
return $data;
}
$zip->close();
}
}
} else {
$this->errors[] = 'File does not exist.';
}
}
public function setFile($path) {
$this->fileData = $this->load($path);
}
public function to_plain_text() {
if ($this->fileData) {
return strip_tags($this->fileData);
} else {
return false;
}
}
public function to_html() {
if ($this->fileData) {
$xml = simplexml_load_string($this->fileData);
$namespaces = $xml->getNamespaces(true);
$children = $xml->children($namespaces['w']);
$html = '<!doctype html><html><head><meta http-equiv="Content-Type" content="text/html;charset=utf-8" /><title></title><style>span.block { display: block; }</style></head><body>';
foreach ($children->body->p as $p) {
$style = '';
$startTags = array();
$startAttrs = array();
if($p->pPr->pStyle) {
$objectAttrs = $p->pPr->pStyle->attributes('w',true);
$objectStyle = (String) $objectAttrs['val'];
if(isset($this->styles[$objectStyle])) {
$startTags = $this->styles[$objectStyle]['tags'];
$startAttrs = $this->styles[$objectStyle]['attrs'];
}
}
if ($p->pPr->spacing) {
$att = $p->pPr->spacing->attributes('w', true);
if (isset($att['before'])) {
$style.='padding-top:' . ($att['before'] / 10) . 'px;';
}
if (isset($att['after'])) {
$style.='padding-bottom:' . ($att['after'] / 10) . 'px;';
}
}
$html.='<span class="block" style="' . $style . '">';
$li = false;
if ($p->pPr->numPr) {
$li = true;
$html.='<li>';
}
foreach ($p->r as $part) {
//echo $part->t;
$tags = $startTags;
$attrs = $startAttrs;
foreach (get_object_vars($part->pPr) as $k => $v) {
if ($k = 'numPr') {
$tags[] = 'li';
}
}
foreach (get_object_vars($part->rPr) as $tag => $style) {
//print_r($style->attributes());
$att = $style->attributes('w', true);
switch ($tag) {
case "b":
$tags[] = 'strong';
break;
case "i":
$tags[] = 'em';
break;
case "color":
//echo (String) $att['val'];
$attrs[] = 'color:#' . $att['val'];
break;
case "sz":
$attrs[] = 'font-size:' . $att['val'] . 'px';
break;
}
}
$openTags = '';
$closeTags = '';
foreach ($tags as $tag) {
$openTags.='<' . $tag . '>';
$closeTags.='</' . $tag . '>';
}
$html.='<span style="' . implode(';', $attrs) . '">' . $openTags . $part->t . $closeTags . '</span>';
}
if ($li) {
$html.='</li>';
}
$html.="</span>";
}
//Trying to weed out non-utf8 stuff from the file:
$regex = <<<'END'
/
(
(?: [\x00-\x7F] # single-byte sequences 0xxxxxxx
| [\xC0-\xDF][\x80-\xBF] # double-byte sequences 110xxxxx 10xxxxxx
| [\xE0-\xEF][\x80-\xBF]{2} # triple-byte sequences 1110xxxx 10xxxxxx * 2
| [\xF0-\xF7][\x80-\xBF]{3} # quadruple-byte sequence 11110xxx 10xxxxxx * 3
){1,100} # ...one or more times
)
| . # anything else
/x
END;
preg_replace($regex, '$1', $html);
return $html . '</body></html>';
exit();
}
}
public function get_errors() {
return $this->errors;
}
private function getStyles() {
}
}

str_replace() in DOM

My current code
$this->data = $this->result->RetrieveDocumentResult;
$this->dom = new DOMDocument();
$this->dom->strictErrorChecking = false;
$this->dom->formatOutput = true;
$this->dom->loadHTML(base64_decode($this->data));
$exceptions = array(
'a' => array('href'),
'img' => array('src')
);
$this->stripAttributes($exceptions);
$this->stripSpanTags();
file_put_contents('Recode/' . $flname . '.html', base64_decode($this->data));
}
public function stripAttributes(array $exceptions)
{
$xpath = new DOMXPath($this->dom);
if (false === ($elements = $xpath->query("//*"))) die('Xpath error!');
/** #var $element DOMElement */
foreach ($elements as $element) {
for ($i = $element->attributes->length; --$i >= 0;) {
$this->tag = $element->nodeName;
$this->attribute = $element->attributes->item($i)->nodeName;
if ($this->checkAttrExceptions($exceptions)) continue;
$element->removeAttribute($this->attribute);
}
}
$this->data = base64_encode($this->dom->saveHTML());
}
public function checkAttrExceptions(array $exceptions)
{
foreach ($exceptions as $tag => $attributes) {
if (empty($attributes) || !is_array($attributes)) {
die('Attributes not set!');
}
foreach ($attributes as $attribute) {
if ($tag === $this->tag && $attribute === $this->attribute) {
return true;
}
}
}
return false;
}
/**
* Strip SPAN tags from current DOM document
*
* #return void
*/
/**
* Strip SPAN tags from current DOM document
*
* #return void
*/
protected function stripSpanTags ()
{
$nodes = $this->dom->getElementsByTagName('span');
while ($span = $nodes->item(0)) {
$replacement = $this->dom->createDocumentFragment();
while ($inner = $span->childNodes->item(0)) {
$replacement->appendChild($inner);
}
$span->parentNode->replaceChild($replacement, $span);
}
$this->data = base64_encode($this->dom->saveHTML());
}
}
Want to remove all in HTML did the following
$html = str_replace(' ', '', $html);
But confused how and where to add this to the first set of codes .. Help me please
Also this should not override previous tag filters in first set of codes
Found Solution ., The following code works
$this->result = $this->soap->RetrieveDocument(
array('format' => 'html')
);
$this->data = $this->result->RetrieveDocumentResult;
$this->dom = new DOMDocument();
$this->dom->strictErrorChecking = false;
$this->dom->formatOutput = true;
$this->dom->loadHTML(base64_decode($this->data));
$exceptions = array(
'a' => array('href'),
'img' => array('src')
);
$this->stripAttributes($exceptions);
$this->stripSpanTags();
$decoded = base64_decode($this->data);
$decoded = $this->stripNonBreakingSpaces($decoded);
file_put_contents('Recode/' . $flname . '.html', $decoded);
}
public function stripAttributes(array $exceptions)
{
$xpath = new DOMXPath($this->dom);
if (false === ($elements = $xpath->query("//*"))) die('Xpath error!');
/** #var $element DOMElement */
foreach ($elements as $element) {
for ($i = $element->attributes->length; --$i >= 0;) {
$this->tag = $element->nodeName;
$this->attribute = $element->attributes->item($i)->nodeName;
if ($this->checkAttrExceptions($exceptions)) continue;
$element->removeAttribute($this->attribute);
}
}
$this->data = base64_encode($this->dom->saveHTML());
}
public function checkAttrExceptions(array $exceptions)
{
foreach ($exceptions as $tag => $attributes) {
if (empty($attributes) || !is_array($attributes)) {
die('Attributes not set!');
}
foreach ($attributes as $attribute) {
if ($tag === $this->tag && $attribute === $this->attribute) {
return true;
}
}
}
return false;
}
/**
* Strip SPAN tags from current DOM document
*
* #return void
*/
/**
* Strip SPAN tags from current DOM document
*
* #return void
*/
protected function stripSpanTags ()
{
$nodes = $this->dom->getElementsByTagName('span');
while ($span = $nodes->item(0)) {
$replacement = $this->dom->createDocumentFragment();
while ($inner = $span->childNodes->item(0)) {
$replacement->appendChild($inner);
}
$span->parentNode->replaceChild($replacement, $span);
}
$this->data = base64_encode($this->dom->saveHTML());
}
/**
* Replace all entities within a string with a regular space
*
* #param string $string Input string
*
* #return string
*/
protected function stripNonBreakingSpaces ($string)
{
return str_replace(' ', ' ', $string);
}
}

Fatal error: Cannot redeclare fputcsv()

I have found a php inventory http://inventory-management.org/ easy but was written in PHP4? and I run now on PHP5. I have found some errors that I have already managed to fix but they are keep coming up so I would like to see if I can managed to run at the end. (As it is really simple script only has 5-7 php files).
Could someone help me please how to fix this error?
Fatal error: Cannot redeclare fputcsv() in C:\xampp\htdocs\Inventory\lib\common.php on line 935
which is:
function fputcsv ($fp, $array, $deliminator=",") {
return fputs($fp, putcsv($array,$delimitator));
}#end fputcsv()
here is the full code:
<?php
/*
*/
/**
* description returns an array with filename base name and the extension
*
* #param filemane format
*
* #return array
*
* #access public
*/
function FileExt($filename) {
//checking if the file have an extension
if (!strstr($filename, "."))
return array("0"=>$filename,"1"=>"");
//peoceed to normal detection
$filename = strrev($filename);
$extpos = strpos($filename , ".");
$file = strrev(substr($filename , $extpos + 1));
$ext = strrev(substr($filename , 0 , $extpos));
return array("0"=>$file,"1"=>$ext);
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function UploadFile($source, $destination , $name ="") {
$name = $name ? $name : basename($source);
$name = FileExt($name);
$name[2]= $name[0];
$counter = 0 ;
while (file_exists( $destination . $name[0] . "." . $name[1] )) {
$name[0] = $name[2] . $counter;
$counter ++;
}
copy($source , $destination . $name[0] . "." . $name[1] );
#chmod($destination . $name[0] . "." . $name[1] , 0777);
}
function UploadFileFromWeb($source, $destination , $name) {
$name = FileExt($name);
$name[2]= $name[0];
$counter = 0 ;
while (file_exists( $destination . $name[0] . "." . $name[1] )) {
$name[0] = $name[2] . $counter;
$counter ++;
}
SaveFileContents($destination . $name[0] . "." . $name[1] , $source);
#chmod($destination . $name[0] . "." . $name[1] , 0777);
}
/**
* returns the contents of a file in a string
*
* #param string $file_name name of file to be loaded
*
* #return string
*
* #acces public
*/
function GetFileContents($file_name) {
// if (!file_exists($file_name)) {
// return null;
// }
//echo "<br>:" . $file_name;
$file = fopen($file_name,"r");
//checking if the file was succesfuly opened
if (!$file)
return null;
if (strstr($file_name,"://"))
while (!feof($file))
$result .= fread($file,1024);
else
$result = #fread($file,filesize($file_name));
fclose($file);
return $result;
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function SaveFileContents($file_name,$content) {
// echo $file_name;
$file = fopen($file_name,"w");
fwrite($file,$content);
fclose($file);
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function Debug($what,$pre = 1,$die = 0) {
if (PB_DEBUG_EXT == 1) {
if ($pre == 1)
echo "<pre style=\"background-color:white;\">";
print_r($what);
if ($pre == 1)
echo "</pre>";
if ($die == 1)
die;
}
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function SendMail($to,$from,$subject,$message,$to_name,$from_name) {
if ($to_name)
$to = "$to_name <$to>";
$headers = "MIME-Version: 1.0\n";
$headers .= "Content-type: text; charset=iso-8859-1\n";
if ($from_name) {
$headers .= "From: $from_name <$from>\n";
$headers .= "Reply-To: $from_name <$from>\n";
}
else {
$headers .= "From: $from\n";
$headers .= "Reply-To: $from\n";
}
$headers .= "X-Mailer: PHP/" . phpversion();
return mail($to, $subject, $message,$headers);
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function FillVars($var,$fields,$with) {
$fields = explode (",",$fields);
foreach ($fields as $field)
if (!$var[$field])
!$var[$field] = $with;
return $var;
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function CleanupString($string,$strip_tags = TRUE) {
$string = addslashes(trim($string));
if ($strip_tags)
$string = strip_tags($string);
return $string;
}
define("RX_EMAIL","^[a-z0-9]+([_\\.-][a-z0-9]+)*#([a-z0-9]+([\.-][a-z0-9]+)*)+\\.[a-z]{2,}$");
define("RX_CHARS","[a-z\ ]");
define("RX_DIGITS","[0-9]");
define("RX_ALPHA","[^a-z0-9_]");
define("RX_ZIP","[0-9\-]");
define("RX_PHONE","[0-9\-\+\(\)]");
/**
* description
*
* #param
*
* #return
*
* #access
*/
function CheckString($string,$min,$max,$regexp = "",$rx_result = FALSE) {
if (get_magic_quotes_gpc() == 0)
$string = CleanupString($string);
if (strlen($string) < $min)
return 1;
elseif (($max != 0) && (strlen($string) > $max))
return 2;
elseif ($regexp != "")
if ($rx_result == eregi($regexp,$string))
return 3;
return 0;
}
/**
* description
*
* #param
*
* #return
*
* #access
*/// FIRST_NAME:S:3:60,LAST_NAME:S...
function ValidateVars($source,$vars) {
$vars = explode(",",$vars);
foreach ($vars as $var) {
list($name,$type,$min,$max) = explode(":",$var);
switch ($type) {
case "S":
$type = RX_CHARS;
$rx_result = FALSE;
break;
case "I":
$type = RX_DIGITS;
$rx_result = TRUE;
break;
case "E":
$type = RX_EMAIL;
$rx_result = FALSE;
break;
case "P":
$type = RX_PHONE;
$rx_result = TRUE;
break;
case "Z":
$type = RX_ZIP;
$rx_result = FALSE;
break;
case "A":
$type = "";
break;
case "F":
//experimental crap
$type = RX_ALPHA;
$rx_result = TRUE;
//$source[strtolower($name)] = str_replace(" ", "" , $source[strtolower($name)] );
break;
}
//var_dump($result);
if (($result = CheckString($source[strtolower($name)],$min,$max,$type,$rx_result)) != 0)
$errors[] = $name;
}
return is_array($errors) ? $errors : 0;
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function ResizeImage($source,$destination,$size) {
if (PB_IMAGE_MAGICK == 1)
system( PB_IMAGE_MAGICK_PATH . "convert $source -resize {$size}x{$size} $destination");
else
copy($source,$destination);
}
/**
* uses microtime() to return the current unix time w/ microseconds
*
* #return float the current unix time in the form of seconds.microseconds
*
* #access public
*/
function GetMicroTime() {
list($usec,$sec) = explode(" ",microtime());
return (float) $usec + (float) $sec;
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function GetArrayPart($input,$from,$count) {
$return = array();
$max = count($input);
for ($i = $from; $i < $from + $count; $i++ )
if ($i<$max)
$return[] = $input[$i];
return $return;
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function ReplaceAllImagesPath($htmldata,$image_path) {
$htmldata = stripslashes($htmldata);
// replacing IE formating style
$htmldata = str_replace("<IMG","<img",$htmldata);
// esmth, i dont know why i'm doing
preg_match_all("'<img.*?>'si",$htmldata,$images);
//<?//ing edit plus
foreach ($images[0] as $image)
$htmldata = str_replace($image,ReplaceImagePath($image,$image_path),$htmldata);
return $htmldata;//implode("\n",$html_out);
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function ReplaceImagePath($image,$replace) {
// removing tags
$image = stripslashes($image);
$image = str_replace("<","",$image);
$image = str_replace(">","",$image);
// exploging image in proprietes
$image_arr = explode(" ",$image);
for ($i = 0;$i < count($image_arr) ;$i++ ) {
if (stristr($image_arr[$i],"src")) {
// lets it :]
$image_arr[$i] = explode("=",$image_arr[$i]);
// modifing the image path
// i doing this
// replacing ',"
$image_arr[$i][1] = str_replace("'","",$image_arr[$i][1]);
$image_arr[$i][1] = str_replace("\"","",$image_arr[$i][1]);
//getting only image name
$image_arr[$i][1] = strrev(substr(strrev($image_arr[$i][1]),0,strpos(strrev($image_arr[$i][1]),"/")));
// building the image back
$image_arr[$i][1] = "\"" . $replace . $image_arr[$i][1] . "\"";
$image_arr[$i] = implode ("=",$image_arr[$i]);
}
}
// adding tags
return "<" . implode(" ",$image_arr) . ">";
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function DowloadAllImages($images,$path) {
foreach ($images as $image)
#SaveFileContents($path ."/".ExtractFileNameFromPath($image),#implode("",#file($image)));
}
function GetAllImagesPath($htmldata) {
$htmldata = stripslashes($htmldata);
// replacing IE formating style
$htmldata = str_replace("<IMG","<img",$htmldata);
// esmth, i dont know why i'm doing
preg_match_all("'<img.*?>'si",$htmldata,$images);
//<?//ing edit plus
foreach ($images[0] as $image)
$images_path[] = GetImageName($image);
return $images_path;
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function GetImagePath($image) {
// removing tags
$image = stripslashes($image);
$image = str_replace("<","",$image);
$image = str_replace(">","",$image);
// exploging image in proprietes
$image_arr = explode(" ",$image);
for ($i = 0;$i < count($image_arr) ;$i++ ) {
if (stristr($image_arr[$i],"src")) {
// lets it :]
$image_arr[$i] = explode("=",$image_arr[$i]);
// modifing the image path
// i doing this
// replacing ',"
$image_arr[$i][1] = str_replace("'","",$image_arr[$i][1]);
$image_arr[$i][1] = str_replace("\"","",$image_arr[$i][1]);
return strrev(substr(strrev($image_arr[$i][1]),0,strpos(strrev($image_arr[$i][1]),"/")));;
}
}
// adding tags
return "";
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function GetImageName($image) {
// removing tags
$image = stripslashes($image);
$image = str_replace("<","",$image);
$image = str_replace(">","",$image);
// exploging image in proprietes
$image_arr = explode(" ",$image);
for ($i = 0;$i < count($image_arr) ;$i++ ) {
if (stristr($image_arr[$i],"src")) {
// lets it :]
$image_arr[$i] = explode("=",$image_arr[$i]);
// modifing the image path
// i doing this
// replacing ',"
$image_arr[$i][1] = str_replace("'","",$image_arr[$i][1]);
$image_arr[$i][1] = str_replace("\"","",$image_arr[$i][1]);
return $image_arr[$i][1];
}
}
// adding tags
return "";
}
/**
* reinventing the wheel [badly]
*
* #param somthin
*
* #return erroneous
*
* #access denied
*/
function ExtractFileNameFromPath($file) {
//return strrev(substr(strrev($file),0,strpos(strrev($file),"/")));
// sau ai putea face asha. umpic mai smart ca mai sus dar tot stupid
// daca le dai path fara slashes i.e. un filename prima returneaza "" asta taie primu char
//return substr($file,strrpos($file,"/") + 1,strlen($file) - strrpos($file,"/"));
// corect ar fi cred asha [observa smart usage`u de strRpos]
//return substr($file,strrpos($file,"/") + (strstr($file,"/") ? 1 : 0),strlen($file) - strrpos($file,"/"));
// sau putem folosi tactica `nute mai caca pe tine and rtm' shi facem asha
return basename($file);
// har har :]]
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function RemoveArraySlashes($array) {
if ($array)
foreach ($array as $key => $item)
if (is_array($item))
$array[$key] = RemoveArraySlashes($item);
else
$array[$key] = stripslashes($item);
return $array;
}
function AddArraySlashes($array) {
if ($array)
foreach ($array as $key => $item)
if (is_array($item))
$array[$key] = AddArraySlashes($item);
else
$array[$key] = addslashes($item);
return $array;
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function Ahtmlentities($array) {
if (is_array($array))
foreach ($array as $key => $item)
if (is_array($item))
$array[$key] = ahtmlentities($item);
else
$array[$key] = htmlentities(stripslashes($item),ENT_COMPAT);
else
return htmlentities(stripslashes($array),ENT_COMPAT);
return $array;
}
function AStripSlasshes($array) {
if (is_array($array))
foreach ($array as $key => $item)
if (is_array($item))
$array[$key] = AStripSlasshes($item);
else
$array[$key] = stripslashes($item);
else
return stripslashes($array);
return $array;
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function Ahtml_entity_decode($array) {
if ($array)
foreach ($array as $key => $item)
if (is_array($item))
$array[$key] = ahtml_entity_decode($item);
else
$array[$key] = html_entity_decode($item,ENT_COMPAT);
return $array;
}
function array2xml ($name, $value, $indent = 1)
{
$indentstring = "\t";
for ($i = 0; $i < $indent; $i++)
{
$indentstring .= $indentstring;
}
if (!is_array($value))
{
$xml = $indentstring.'<'.$name.'>'.$value.'</'.$name.'>'."\n";
}
else
{
if($indent === 1)
{
$isindex = False;
}
else
{
$isindex = True;
while (list ($idxkey, $idxval) = each ($value))
{
if ($idxkey !== (int)$idxkey)
{
$isindex = False;
}
}
}
reset($value);
while (list ($key, $val) = each ($value))
{
if($indent === 1)
{
$keyname = $name;
$nextkey = $key;
}
elseif($isindex)
{
$keyname = $name;
$nextkey = $name;
}
else
{
$keyname = $key;
$nextkey = $key;
}
if (is_array($val))
{
$xml .= $indentstring.'<'.$keyname.'>'."\n";
$xml .= array2xml ($nextkey, $val, $indent+1);
$xml .= $indentstring.'</'.$keyname.'>'."\n";
}
else
{
$xml .= array2xml ($nextkey, $val, $indent);
}
}
}
return $xml;
}
function GetPhpContent($file) {
if (file_exists($file) ) {
$data = GetFileContents($file);
//replacing special chars in content
$data = str_replace("<?php","",$data);
$data = str_replace("?>","",$data);
return $data;
}
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function KeyArray($array,$recurse = 0 , $count = 1) {
if (is_array($array)) {
foreach ($array as $key => $val) {
$array[$key]["key"] = $count ++;
if ($recurse) {
foreach ($array[$key] as $k => $val)
if (is_array($val)) {
KeyArray($array[$key][$k] , $recurse , $count);
}
}
}
}
return $count + 1;
}
function RandomWord( $passwordLength ) {
$password = "";
for ($index = 1; $index <= $passwordLength; $index++) {
// Pick random number between 1 and 62
$randomNumber = rand(1, 62);
// Select random character based on mapping.
if ($randomNumber < 11)
$password .= Chr($randomNumber + 48 - 1); // [ 1,10] => [0,9]
else if ($randomNumber < 37)
$password .= Chr($randomNumber + 65 - 10); // [11,36] => [A,Z]
else
$password .= Chr($randomNumber + 97 - 36); // [37,62] => [a,z]
}
return $password;
}
function DeleteFolder($file) {
if (file_exists($file)) {
chmod($file,0777);
if (is_dir($file)) {
$handle = opendir($file);
while($filename = readdir($handle)) {
if ($filename != "." && $filename != "..") {
DeleteFolder($file."/".$filename);
}
}
closedir($handle);
rmdir($file);
} else {
unlink($file);
}
}
}
function GenerateRecordID($array) {
$max = 0;
if (is_array($array)) {
foreach ($array as $key => $val)
$max = ($key > $max ? $key : $max);
return $max + 1;
}
else return 1;
}
/*****************************************************
Links cripting for admin
DO NOT TOUCH UNLKESS YOU KNOW WHAT YOU ARE DOING
*****************************************************/
/**
* description
*
* #param
*
* #return
*
* #access
*/
function CryptLink($link) {
if (defined("PB_CRYPT_LINKS") && (PB_CRYPT_LINKS == 1)) {
if (stristr($link,"javascript:")) {
/* if (stristr($link,"window.location=")) {
$pos = strpos($link , "window.location=");
$js = substr($link , 0 , $pos + 17 );
$final = substr($link , $pos + 17 );
$final = substr($final, 0, strlen($final) - 1 );
//well done ... crypt the link now
$url = #explode("?" , $final);
if (!is_array($url))
$url[0] = $final;
$tmp = str_replace( $url[0] . "?" , "" , $final);
$uri = urlencode(urlencode(base64_encode(str_rot13($tmp))));
$link = $js . $url[0] . "?" . $uri . md5($uri) . "'";
}
*/
} else {
$url = #explode("?" , $link);
if (!is_array($url))
$url[0] = $link;
$tmp = str_replace( $url[0] . "?" , "" , $link);
$uri = urlencode(urlencode(base64_encode(str_rot13($tmp))));
$link = $url[0] . "?" . $uri . md5($uri);
}
}
return $link;
}
/************************************************************************/
/* SOME PREINITIALISATION CRAP*/
if (defined("PB_CRYPT_LINKS") && (PB_CRYPT_LINKS == 1) ) {
$key = key($_GET);
if (is_array($_GET) && (count($_GET) == 1) && ($_GET[$key] == "")) {
$tmp = $_SERVER["QUERY_STRING"];
//do the md5 check
$md5 = substr($tmp , -32);
$tmp = substr($tmp , 0 , strlen($tmp) - 32);
if ($md5 != md5($tmp)) {
//header("index.php?action=badrequest");
//exit;
die("Please dont change the links!");
}
$tmp = str_rot13(base64_decode(urldecode(urldecode($tmp))));
$tmp_array = #explode("&" , $tmp);
$tmp_array = is_array($tmp_array) ? $tmp_array : array($tmp);
if (is_array($tmp_array)) {
foreach ($tmp_array as $key => $val) {
$tmp2 = explode("=" , $val);
$out[$tmp2[0]] = $tmp2[1];
}
} else {
$tmp2 = explode("=" , $tmp);
$out[$tmp2[0]] = $tmp2[1];
}
$_GET = $out;
}
}
/***********************************************************************/
function ArrayReplace($what , $with , $array ) {
if ($array)
foreach ($array as $key => $item)
if (is_array($item))
$array[$key] = ArrayReplace($what , $with , $item);
else
$array[$key] = str_replace($what , $with , $item);
return $array;
}
function stri_replace( $find, $replace, $string )
{
$parts = explode( strtolower($find), strtolower($string) );
$pos = 0;
foreach( $parts as $key=>$part ){
$parts[ $key ] = substr($string, $pos, strlen($part));
$pos += strlen($part) + strlen($find);
}
return( join( $replace, $parts ) );
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function GMTDate($format , $date) {
global $_GMT;
return date($format , $date - $_GMT);
}
function putcsv ($array, $deliminator=",") {
$line = "";
foreach($array as $val) {
# remove any windows new lines,
# as they interfere with the parsing at the other end
$val = str_replace("\r\n", "\n", $val);
# if a deliminator char, a double quote char or a newline
# are in the field, add quotes
if(ereg("[$deliminator\"\n\r]", $val)) {
$val = '"'.str_replace('"', '""', $val).'"';
}#end if
$line .= $val.$deliminator;
}#end foreach
# strip the last deliminator
$line = substr($line, 0, (strlen($deliminator) * -1));
# add the newline
$line .= "\n";
# we don't care if the file pointer is invalid,
# let fputs take care of it
return $line;
}#end fputcsv()
function fputcsv ($fp, $array, $deliminator=",") {
return fputs($fp, putcsv($array,$delimitator));
}#end fputcsv()
/**
* description
*
* #param
*
* #return
*
* #access
*/
function is_subaction($sub,$action) {
return (bool)($_GET["sub"] == $sub) && ($_GET["action"] == $action);
}
?>
many thanks in advance
fputcsv() is a built in PHP function. This means you cannot name your own function the same thing.
If you need this code to work with PHP4, just check to see if the function exists first, then if not, create your own.
if (!function_exists('fputcsv')) {
// Your definition here
}

Fix bug in PayPal PHP SDK Core

I am having trouble find the problem in figuring out the problem using merchant-sdk-php I found on github. For some reason its throwing this error. I tried looking at the code but I dont under stand it or see the problem.
Fatal error: Call to undefined method stdClass::toXMLString() in /home/content/08/10639508/html/wp-content/plugins/donation-manager/library/vendor/paypal/paypal-sdk-core-php-bc7822a/lib/PPXmlMessage.php on line 89
<?php
/**
* #author
*/
abstract class PPXmlMessage
{
/**
* #return string
*/
public function toSOAP()
{
return $this->toXMLString();
}
/**
* #return string
*/
public function toXMLString()
{
if (count($properties = get_object_vars($this)) >= 2 && array_key_exists('value', $properties)) {
$attributes = array();
foreach (array_keys($properties) as $property) {
if ($property === 'value') continue;
if (($annots = PPUtils::propertyAnnotations($this, $property)) && isset($annots['attribute'])) {
if (($propertyValue = $this->{$property}) === NULL || $propertyValue == NULL) {
$attributes[] = NULL;
continue;
}
$attributes[] = $property . '="' . PPUtils::escapeInvalidXmlCharsRegex($propertyValue) . '"';
}
}
if (count($attributes)) {
return implode(' ', $attributes) . '>' . PPUtils::escapeInvalidXmlCharsRegex($this->value);
}
}
$xml = array();
foreach ($properties as $property => $defaultValue) {
if (($propertyValue = $this->{$property}) === NULL || $propertyValue == NULL) {
continue;
}
if (is_array($defaultValue) || is_array($propertyValue)) {
foreach ($propertyValue as $item) {
if (!is_object($item)) {
$xml[] = $this->buildProperty($property, $item);
}else{
$xml[] = $this->buildProperty($property, $item);
}
}
} else {
$xml[] = $this->buildProperty($property, $propertyValue);
}
}
return implode($xml);
}
/**
* #param string $property
* #param PPXmlMessage|string $value
* #param string $namespace
* #return string
*/
private function buildProperty($property, $value, $namespace = 'ebl')
{
$annotations = PPUtils::propertyAnnotations($this, $property);
if (!empty($annotations['namespace'])) {
$namespace = $annotations['namespace'];
}
if (!empty($annotations['name'])) {
$property = $annotations['name'];
}
$el = '<' . $namespace . ':' . $property;
if (!is_object($value)) {
$el .= '>' . PPUtils::escapeInvalidXmlCharsRegex($value);
} else {
if (substr($value = $value->toXMLString(), 0, 1) === '<' || $value=='') {
$el .= '>' . $value;
} else {
$el .= ' ' . $value;
}
}
return $el . '</' . $namespace . ':' . $property . '>';
}
/**
* #param array $map
* #param string $prefix
*/
public function init(array $map = array(), $prefix = '')
{
if (empty($map)) {
return;
}
if (($first = reset($map)) && !is_array($first) && !is_numeric(key($map))) {
parent::init($map, $prefix);
return;
}
$propertiesMap = PPUtils::objectProperties($this);
$arrayCtr = array();
foreach ($map as $element) {
if (empty($element) || empty($element['name'])) {
continue;
} elseif (!array_key_exists($property = strtolower($element['name']), $propertiesMap)) {
if (!preg_match('~^(.+)[\[\(](\d+)[\]\)]$~', $property, $m)) {
continue;
}
$element['name'] = $m[1];
$element['num'] = $m[2];
}
$element['name'] = $propertiesMap[strtolower($element['name'])];
if(PPUtils::isPropertyArray($this, $element['name'])) {
$arrayCtr[$element['name']] = isset($arrayCtr[$element['name']]) ? ($arrayCtr[$element['name']]+1) : 0;
$element['num'] = $arrayCtr[$element['name']];
}
if (!empty($element["attributes"]) && is_array($element["attributes"])) {
foreach ($element["attributes"] as $key => $val) {
$element["children"][] = array(
'name' => $key,
'text' => $val,
);
}
if (isset($element['text'])) {
$element["children"][] = array(
'name' => 'value',
'text' => $element['text'],
);
}
$this->fillRelation($element['name'], $element);
} elseif (!empty($element['text'])) {
$this->{$element['name']} = $element['text'];
} elseif (!empty($element["children"]) && is_array($element["children"])) {
$this->fillRelation($element['name'], $element);
}
}
}
/**
* #param string $property
* #param array $element
*/
private function fillRelation($property, array $element)
{
if (!class_exists($type = PPUtils::propertyType($this, $property))) {
trigger_error("Class $type not found.", E_USER_NOTICE);
return; // just ignore
}
if (isset($element['num'])) { // array of objects
$this->{$property}[$element['num']] = $item = new $type();
$item->init($element['children']);
} else {
$this->{$property} = new $type();
$this->{$property}->init($element["children"]);
}
}
}
I had this exact same error (with my live application - it worked fine in my test code). I eventually realized that, when I copied over my test code into the live environment and changed my credentials and URLs from the sandbox ones to the live ones ... I somehow deleted a line of code initializing a PaymentDetailsType object before calling SetExpressCheckout. So this error seemed pretty unrelated, but it was just a problem with setting up the objects before making the call to PayPal.
Perchance are you using json_encode/decode on your PaymentDetail record? It seems that PayPal is very particular about the component classes; stdClass (which json_decode generates) won't cut it. Serialize works, but there are warnings about using it.

PHP Object as XML Document

What is the best way to take a given PHP object and serialize it as XML? I am looking at simple_xml and I have used it to parse XML into objects, but it isn't clear to me how it works the other way around.
I'd agree with using PEAR's XML_Serializer, but if you want something simple that supports objects/arrays that have properties nested, you can use this.
class XMLSerializer {
// functions adopted from http://www.sean-barton.co.uk/2009/03/turning-an-array-or-object-into-xml-using-php/
public static function generateValidXmlFromObj(stdClass $obj, $node_block='nodes', $node_name='node') {
$arr = get_object_vars($obj);
return self::generateValidXmlFromArray($arr, $node_block, $node_name);
}
public static function generateValidXmlFromArray($array, $node_block='nodes', $node_name='node') {
$xml = '<?xml version="1.0" encoding="UTF-8" ?>';
$xml .= '<' . $node_block . '>';
$xml .= self::generateXmlFromArray($array, $node_name);
$xml .= '</' . $node_block . '>';
return $xml;
}
private static function generateXmlFromArray($array, $node_name) {
$xml = '';
if (is_array($array) || is_object($array)) {
foreach ($array as $key=>$value) {
if (is_numeric($key)) {
$key = $node_name;
}
$xml .= '<' . $key . '>' . self::generateXmlFromArray($value, $node_name) . '</' . $key . '>';
}
} else {
$xml = htmlspecialchars($array, ENT_QUOTES);
}
return $xml;
}
}
take a look at PEAR's XML_Serializer package. I've used it with pretty good results. You can feed it arrays, objects etc and it will turn them into XML. It also has a bunch of options like picking the name of the root node etc.
Should do the trick
not quite an answer to the original question, but the way i solved my problem with this was by declaring my object as:
$root = '<?xml version="1.0" encoding="UTF-8"?><Activities/>';
$object = new simpleXMLElement($root);
as opposed to:
$object = new stdClass;
before i started adding any values!
Use a dom function to do it:
http://www.php.net/manual/en/function.dom-import-simplexml.php
Import the SimpleXML object and then save. The above link contains an example. :)
In a nutshell:
<?php
$array = array('hello' => 'world', 'good' => 'morning');
$xml = simplexml_load_string("<?xml version='1.0' encoding='utf-8'?><foo />");
foreach ($array as $k=>$v) {
$xml->addChild($k, $v);
}
?>
take a look at my version
class XMLSerializer {
/**
*
* The most advanced method of serialization.
*
* #param mixed $obj => can be an objectm, an array or string. may contain unlimited number of subobjects and subarrays
* #param string $wrapper => main wrapper for the xml
* #param array (key=>value) $replacements => an array with variable and object name replacements
* #param boolean $add_header => whether to add header to the xml string
* #param array (key=>value) $header_params => array with additional xml tag params
* #param string $node_name => tag name in case of numeric array key
*/
public static function generateValidXmlFromMixiedObj($obj, $wrapper = null, $replacements=array(), $add_header = true, $header_params=array(), $node_name = 'node')
{
$xml = '';
if($add_header)
$xml .= self::generateHeader($header_params);
if($wrapper!=null) $xml .= '<' . $wrapper . '>';
if(is_object($obj))
{
$node_block = strtolower(get_class($obj));
if(isset($replacements[$node_block])) $node_block = $replacements[$node_block];
$xml .= '<' . $node_block . '>';
$vars = get_object_vars($obj);
if(!empty($vars))
{
foreach($vars as $var_id => $var)
{
if(isset($replacements[$var_id])) $var_id = $replacements[$var_id];
$xml .= '<' . $var_id . '>';
$xml .= self::generateValidXmlFromMixiedObj($var, null, $replacements, false, null, $node_name);
$xml .= '</' . $var_id . '>';
}
}
$xml .= '</' . $node_block . '>';
}
else if(is_array($obj))
{
foreach($obj as $var_id => $var)
{
if(!is_object($var))
{
if (is_numeric($var_id))
$var_id = $node_name;
if(isset($replacements[$var_id])) $var_id = $replacements[$var_id];
$xml .= '<' . $var_id . '>';
}
$xml .= self::generateValidXmlFromMixiedObj($var, null, $replacements, false, null, $node_name);
if(!is_object($var))
$xml .= '</' . $var_id . '>';
}
}
else
{
$xml .= htmlspecialchars($obj, ENT_QUOTES);
}
if($wrapper!=null) $xml .= '</' . $wrapper . '>';
return $xml;
}
/**
*
* xml header generator
* #param array $params
*/
public static function generateHeader($params = array())
{
$basic_params = array('version' => '1.0', 'encoding' => 'UTF-8');
if(!empty($params))
$basic_params = array_merge($basic_params,$params);
$header = '<?xml';
foreach($basic_params as $k=>$v)
{
$header .= ' '.$k.'='.$v;
}
$header .= ' ?>';
return $header;
}
}
use WDDX:
http://uk.php.net/manual/en/wddx.examples.php
(if this extension is installed)
it's dedicated to that:
http://www.openwddx.org/
Here is my code used for serializing PHP objects to XML "understandable" by Microsoft .NET XmlSerializer.Deserialize
class XMLSerializer {
/**
* Get object class name without namespace
* #param object $object Object to get class name from
* #return string Class name without namespace
*/
private static function GetClassNameWithoutNamespace($object) {
$class_name = get_class($object);
return end(explode('\\', $class_name));
}
/**
* Converts object to XML compatible with .NET XmlSerializer.Deserialize
* #param type $object Object to serialize
* #param type $root_node Root node name (if null, objects class name is used)
* #return string XML string
*/
public static function Serialize($object, $root_node = null) {
$xml = '<?xml version="1.0" encoding="UTF-8" ?>';
if (!$root_node) {
$root_node = self::GetClassNameWithoutNamespace($object);
}
$xml .= '<' . $root_node . ' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">';
$xml .= self::SerializeNode($object);
$xml .= '</' . $root_node . '>';
return $xml;
}
/**
* Create XML node from object property
* #param mixed $node Object property
* #param string $parent_node_name Parent node name
* #param bool $is_array_item Is this node an item of an array?
* #return string XML node as string
* #throws Exception
*/
private static function SerializeNode($node, $parent_node_name = false, $is_array_item = false) {
$xml = '';
if (is_object($node)) {
$vars = get_object_vars($node);
} else if (is_array($node)) {
$vars = $node;
} else {
throw new Exception('Coś poszło nie tak');
}
foreach ($vars as $k => $v) {
if (is_object($v)) {
$node_name = ($parent_node_name ? $parent_node_name : self::GetClassNameWithoutNamespace($v));
if (!$is_array_item) {
$node_name = $k;
}
$xml .= '<' . $node_name . '>';
$xml .= self::SerializeNode($v);
$xml .= '</' . $node_name . '>';
} else if (is_array($v)) {
$xml .= '<' . $k . '>';
if (count($v) > 0) {
if (is_object(reset($v))) {
$xml .= self::SerializeNode($v, self::GetClassNameWithoutNamespace(reset($v)), true);
} else {
$xml .= self::SerializeNode($v, gettype(reset($v)), true);
}
} else {
$xml .= self::SerializeNode($v, false, true);
}
$xml .= '</' . $k . '>';
} else {
$node_name = ($parent_node_name ? $parent_node_name : $k);
if ($v === null) {
continue;
} else {
$xml .= '<' . $node_name . '>';
if (is_bool($v)) {
$xml .= $v ? 'true' : 'false';
} else {
$xml .= htmlspecialchars($v, ENT_QUOTES);
}
$xml .= '</' . $node_name . '>';
}
}
}
return $xml;
}
}
example:
class GetProductsCommandResult {
public $description;
public $Errors;
}
class Error {
public $id;
public $error;
}
$obj = new GetProductsCommandResult();
$obj->description = "Teścik";
$obj->Errors = array();
$obj->Errors[0] = new Error();
$obj->Errors[0]->id = 666;
$obj->Errors[0]->error = "Sth";
$obj->Errors[1] = new Error();
$obj->Errors[1]->id = 666;
$obj->Errors[1]->error = null;
$xml = XMLSerializer::Serialize($obj);
results in:
<?xml version="1.0" encoding="UTF-8"?>
<GetProductsCommandResult xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<description>Teścik</description>
<Errors>
<Error>
<id>666</id>
<error>Sth</error>
</Error>
<Error>
<id>666</id>
</Error>
</Errors>
</GetProductsCommandResult>
I know this is an old question, but recently I had to generate complex XML structures.
My approach contains advanced OOP principles. The idea is to serialize the parent object who contains multiple children and subchildren.
Nodes get names from the class names but you can override the class name with the first parameter when creating an object for serialization.
You can create: a Simple node, without child nodes, EntityList and ArrayList. EntityList is a list of objects of the same class, but an ArrayList may have different objects.
Each object has to extend the abstract class SerializeXmlAbstract in order to match first input parameter in class: Object2xml, method serialize($object, $name = NULL, $prefix = FALSE).
By default, if you don't provide the second parameter, the root XML node will have the class name of the given object. The third parameter indicates if root node name has a prefix or not. Prefix is hardcoded as a private property in Export2xml class.
interface SerializeXml {
public function hasAttributes();
public function getAttributes();
public function setAttributes($attribs = array());
public function getNameOwerriden();
public function isNameOwerriden();
}
abstract class SerializeXmlAbstract implements SerializeXml {
protected $attributes;
protected $nameOwerriden;
function __construct($name = NULL) {
$this->nameOwerriden = $name;
}
public function getAttributes() {
return $this->attributes;
}
public function getNameOwerriden() {
return $this->nameOwerriden;
}
public function setAttributes($attribs = array()) {
$this->attributes = $attribs;
}
public function hasAttributes() {
return (is_array($this->attributes) && count($this->attributes) > 0) ? TRUE : FALSE;
}
public function isNameOwerriden() {
return $this->nameOwerriden != NULL ? TRUE : FALSE;
}
}
abstract class Entity_list extends SplObjectStorage {
protected $_listItemType;
public function __construct($type) {
$this->setListItemType($type);
}
private function setListItemType($param) {
$this->_listItemType = $param;
}
public function detach($object) {
if ($object instanceOf $this->_listItemType) {
parent::detach($object);
}
}
public function attach($object, $data = null) {
if ($object instanceOf $this->_listItemType) {
parent::attach($object, $data);
}
}
}
abstract class Array_list extends SerializeXmlAbstract {
protected $_listItemType;
protected $_items;
public function __construct() {
//$this->setListItemType($type);
$this->_items = new SplObjectStorage();
}
protected function setListItemType($param) {
$this->_listItemType = $param;
}
public function getArray() {
$return = array();
$this->_items->rewind();
while ($this->_items->valid()) {
$return[] = $this->_items->current();
$this->_items->next();
}
// print_r($return);
return $return;
}
public function detach($object) {
if ($object instanceOf $this->_listItemType) {
if (in_array($this->_items->contains($object))) {
$this->_items->detach($object);
}
}
}
public function attachItem($ob) {
$this->_items->attach($ob);
}
}
class Object2xml {
public $rootPrefix = "ernm";
private $addPrefix;
public $xml;
public function serialize($object, $name = NULL, $prefix = FALSE) {
if ($object instanceof SerializeXml) {
$this->xml = new DOMDocument('1.0', 'utf-8');
$this->xml->appendChild($this->object2xml($object, $name, TRUE));
$this->xml->formatOutput = true;
echo $this->xml->saveXML();
} else {
die("Not implement SerializeXml interface");
}
}
protected function object2xml(SerializeXmlAbstract $object, $nodeName = NULL, $prefix = null) {
$single = property_exists(get_class($object), "value");
$nName = $nodeName != NULL ? $nodeName : get_class($object);
if ($prefix) {
$nName = $this->rootPrefix . ":" . $nName;
}
if ($single) {
$ref = $this->xml->createElement($nName);
} elseif (is_object($object)) {
if ($object->isNameOwerriden()) {
$nodeName = $object->getNameOwerriden();
}
$ref = $this->xml->createElement($nName);
if ($object->hasAttributes()) {
foreach ($object->getAttributes() as $key => $value) {
$ref->setAttribute($key, $value);
}
}
foreach (get_object_vars($object) as $n => $prop) {
switch (gettype($prop)) {
case "object":
if ($prop instanceof SplObjectStorage) {
$ref->appendChild($this->handleList($n, $prop));
} elseif ($prop instanceof Array_list) {
$node = $this->object2xml($prop);
foreach ($object->ResourceGroup->getArray() as $key => $value) {
$node->appendChild($this->object2xml($value));
}
$ref->appendChild($node);
} else {
$ref->appendChild($this->object2xml($prop));
}
break;
default :
if ($prop != null) {
$ref->appendChild($this->xml->createElement($n, $prop));
}
break;
}
}
} elseif (is_array($object)) {
foreach ($object as $value) {
$ref->appendChild($this->object2xml($value));
}
}
return $ref;
}
private function handleList($name, SplObjectStorage $param, $nodeName = NULL) {
$lst = $this->xml->createElement($nodeName == NULL ? $name : $nodeName);
$param->rewind();
while ($param->valid()) {
if ($param->current() != null) {
$lst->appendChild($this->object2xml($param->current()));
}
$param->next();
}
return $lst;
}
}
This is code you need to be able to get valid xml from objects. Next sample produces this xml:
<InsertMessage priority="high">
<NodeSimpleValue firstAttrib="first" secondAttrib="second">simple value</NodeSimpleValue>
<Arrarita>
<Title>PHP OOP is great</Title>
<SequenceNumber>1</SequenceNumber>
<Child>
<FirstChild>Jimmy</FirstChild>
</Child>
<Child2>
<FirstChild>bird</FirstChild>
</Child2>
</Arrarita>
<ThirdChild>
<NodeWithChilds>
<FirstChild>John</FirstChild>
<ThirdChild>James</ThirdChild>
</NodeWithChilds>
<NodeWithChilds>
<FirstChild>DomDocument</FirstChild>
<SecondChild>SplObjectStorage</SecondChild>
</NodeWithChilds>
</ThirdChild>
</InsertMessage>
Classes needed for this xml are:
class NodeWithArrayList extends Array_list {
public $Title;
public $SequenceNumber;
public function __construct($name = NULL) {
echo $name;
parent::__construct($name);
}
}
class EntityListNode extends Entity_list {
public function __construct($name = NULL) {
parent::__construct($name);
}
}
class NodeWithChilds extends SerializeXmlAbstract {
public $FirstChild;
public $SecondChild;
public $ThirdChild;
public function __construct($name = NULL) {
parent::__construct($name);
}
}
class NodeSimpleValue extends SerializeXmlAbstract {
protected $value;
public function getValue() {
return $this->value;
}
public function setValue($value) {
$this->value = $value;
}
public function __construct($name = NULL) {
parent::__construct($name);
}
}
And finally code that instantiate objects is:
$firstChild = new NodeSimpleValue("firstChild");
$firstChild->setValue( "simple value" );
$firstChild->setAttributes(array("firstAttrib" => "first", "secondAttrib" => "second"));
$secondChild = new NodeWithArrayList("Arrarita");
$secondChild->Title = "PHP OOP is great";
$secondChild->SequenceNumber = 1;
$firstListItem = new NodeWithChilds();
$firstListItem->FirstChild = "John";
$firstListItem->ThirdChild = "James";
$firstArrayItem = new NodeWithChilds("Child");
$firstArrayItem->FirstChild = "Jimmy";
$SecondArrayItem = new NodeWithChilds("Child2");
$SecondArrayItem->FirstChild = "bird";
$secondListItem = new NodeWithChilds();
$secondListItem->FirstChild = "DomDocument";
$secondListItem->SecondChild = "SplObjectStorage";
$secondChild->attachItem($firstArrayItem);
$secondChild->attachItem($SecondArrayItem);
$list = new EntityListNode("NodeWithChilds");
$list->attach($firstListItem);
$list->attach($secondListItem);
$message = New NodeWithChilds("InsertMessage");
$message->setAttributes(array("priority" => "high"));
$message->FirstChild = $firstChild;
$message->SecondChild = $secondChild;
$message->ThirdChild = $list;
$object2xml = new Object2xml();
$object2xml->serialize($message, "xml", TRUE);
Hope it will help someone.
Cheers,
Siniša
Use recursive method, like this:
private function ReadProperty($xmlElement, $object) {
foreach ($object as $key => $value) {
if ($value != null) {
if (is_object($value)) {
$element = $this->xml->createElement($key);
$this->ReadProperty($element, $value);
$xmlElement->AppendChild($element);
} elseif (is_array($value)) {
$this->ReadProperty($xmlElement, $value);
} else {
$this->AddAttribute($xmlElement, $key, $value);
}
}
}
}
Here the complete example:
http://www.tyrodeveloper.com/2018/09/convertir-clase-en-xml-con-php.html
I recently created a class available via git that resolves this problem:
https://github.com/zappz88/XMLSerializer
Here is the class structure, and keep in mind that you will need to define the root properly for format proper xml:
class XMLSerializer {
private $OpenTag = "<";
private $CloseTag = ">";
private $BackSlash = "/";
public $Root = "root";
public function __construct() {
}
private function Array_To_XML($array, $arrayElementName = "element_", $xmlString = "")
{
if($xmlString === "")
{
$xmlString = "{$this->OpenTag}{$this->Root}{$this->CloseTag}";
}
$startTag = "{$this->OpenTag}{$arrayElementName}{$this->CloseTag}";
$xmlString .= $startTag;
foreach($array as $key => $value){
if(gettype($value) === "string" || gettype($value) === "boolean" || gettype($value) === "integer" || gettype($value) === "double" || gettype($value) === "float")
{
$elementStartTag = "{$this->OpenTag}{$arrayElementName}_{$key}{$this->CloseTag}";
$elementEndTag = "{$this->OpenTag}{$this->BackSlash}{$arrayElementName}_{$key}{$this->CloseTag}";
$xmlString .= "{$elementStartTag}{$value}{$elementEndTag}";
continue;
}
else if(gettype($value) === "array")
{
$xmlString = $this->Array_To_XML($value, $arrayElementName, $xmlString);
continue;
}
else if(gettype($value) === "object")
{
$xmlString = $this->Object_To_XML($value, $xmlString);
continue;
}
else
{
continue;
}
}
$endTag = "{$this->OpenTag}{$this->BackSlash}{$arrayElementName}{$this->CloseTag}";
$xmlString .= $endTag;
return $xmlString;
}
private function Object_To_XML($objElement, $xmlString = "")
{
if($xmlString === "")
{
$xmlString = "{$this->OpenTag}{$this->Root}{$this->CloseTag}";
}
foreach($objElement as $key => $value){
if(gettype($value) !== "array" && gettype($value) !== "object")
{
$startTag = "{$this->OpenTag}{$key}{$this->CloseTag}";
$endTag = "{$this->OpenTag}{$this->BackSlash}{$key}{$this->CloseTag}";
$xmlString .= "{$startTag}{$value}{$endTag}";
continue;
}
else if(gettype($value) === "array")
{
$xmlString = $this->Array_To_XML($value, $key, $xmlString);
continue;
}
else if(gettype($value) === "object")
{
$xmlString = $this->Object_To_XML($value, $xmlString);
continue;
}
else
{
continue;
}
}
return $xmlString;
}
public function Serialize_Object($element, $xmlString = "")
{
$endTag = "{$this->OpenTag}{$this->BackSlash}{$this->Root}{$this->CloseTag}";
return "{$this->Object_To_XML($element, $xmlString)}{$endTag}";
}
public function Serialize_Array($element, $xmlString = "")
{
$endTag = "{$this->OpenTag}{$this->BackSlash}{$this->Root}{$this->CloseTag}";
return "{$this->Array_To_XML($element, $xmlString)}{$endTag}";
}
}
While I agree with #philfreo and his reasoning that you shouldn't be dependant on PEAR, his solution is still not quite there. There are potential issues when the key could be a string that contains any of the following characters:
<
>
\s (space)
"
'
Any of these will throw off the format, as XML uses these characters in its grammar. So, without further ado, here is a simple solution to that very possible occurrence:
function xml_encode( $var, $indent = false, $i = 0 ) {
$version = "1.0";
if ( !$i ) {
$data = '<?xml version="1.0"?>' . ( $indent ? "\r\n" : '' )
. '<root vartype="' . gettype( $var ) . '" xml_encode_version="'. $version . '">' . ( $indent ? "\r\n" : '' );
}
else {
$data = '';
}
foreach ( $var as $k => $v ) {
$data .= ( $indent ? str_repeat( "\t", $i ) : '' ) . '<var vartype="' .gettype( $v ) . '" varname="' . htmlentities( $k ) . '"';
if($v == "") {
$data .= ' />';
}
else {
$data .= '>';
if ( is_array( $v ) ) {
$data .= ( $indent ? "\r\n" : '' ) . xml_encode( $v, $indent, $verbose, ($i + 1) ) . ( $indent ? str_repeat("\t", $i) : '' );
}
else if( is_object( $v ) ) {
$data .= ( $indent ? "\r\n" : '' ) . xml_encode( json_decode( json_encode( $v ), true ), $indent, $verbose, ($i + 1)) . ($indent ? str_repeat("\t", $i) : '');
}
else {
$data .= htmlentities( $v );
}
$data .= '</var>';
}
$data .= ($indent ? "\r\n" : '');
}
if ( !$i ) {
$data .= '</root>';
}
return $data;
}
Here is a sample usage:
// sample object
$tests = Array(
"stringitem" => "stringvalue",
"integeritem" => 1,
"floatitem" => 1.00,
"arrayitems" => Array("arrayvalue1", "arrayvalue2"),
"hashitems" => Array( "hashkey1" => "hashkey1value", "hashkey2" => "hashkey2value" ),
"literalnull" => null,
"literalbool" => json_decode( json_encode( 1 ) )
);
// add an objectified version of itself as a child
$tests['objectitem'] = json_decode( json_encode( $tests ), false);
// convert and output
echo xml_encode( $tests );
/*
// output:
<?xml version="1.0"?>
<root vartype="array" xml_encode_version="1.0">
<var vartype="integer" varname="integeritem">1</var>
<var vartype="string" varname="stringitem">stringvalue</var>
<var vartype="double" varname="floatitem">1</var>
<var vartype="array" varname="arrayitems">
<var vartype="string" varname="0">arrayvalue1</var>
<var vartype="string" varname="1">arrayvalue2</var>
</var>
<var vartype="array" varname="hashitems">
<var vartype="string" varname="hashkey1">hashkey1value</var>
<var vartype="string" varname="hashkey2">hashkey2value</var>
</var>
<var vartype="NULL" varname="literalnull" />
<var vartype="integer" varname="literalbool">1</var>
<var vartype="object" varname="objectitem">
<var vartype="string" varname="stringitem">stringvalue</var>
<var vartype="integer" varname="integeritem">1</var>
<var vartype="integer" varname="floatitem">1</var>
<var vartype="array" varname="arrayitems">
<var vartype="string" varname="0">arrayvalue1</var>
<var vartype="string" varname="1">arrayvalue2</var>
</var>
<var vartype="array" varname="hashitems">
<var vartype="string" varname="hashkey1">hashkey1value</var>
<var vartype="string" varname="hashkey2">hashkey2value</var>
</var>
<var vartype="NULL" varname="literalnull" />
<var vartype="integer" varname="literalbool">1</var>
</var>
</root>
*/
Notice that the key names are stored in the varname attribute (html encoded), and even the type is stored, so symmetric de-serialization is possible. There is only one issue with this: it will not serialize classes, only the instantiated object, which will not include the class methods. This is only functional for passing "data" back and forth.
I hope this helps someone, even though this was answered long ago.
Well, while a little dirty, you could always run a loop on the object's properties...
$_xml = '';
foreach($obj as $key => $val){
$_xml .= '<' . $key . '>' . $val . '</' . $key . ">\n";
}
Using fopen/fwrite/fclose you could generate an XML doc with the $_xml variable as content. It's ugly, but it would work.

Categories