Location: PHPKode > scripts > Binary XML > binary-xml/BinaryXML.php
<?php
/**
 * This is an example to demonstatrate how we can embed binary in XML. Here an array of images path
 * given to generateBinaryXML method and XML document saved in the given path. savePath should be a
 * physical path because images are large in size and results large XML document.
 * hide@address.com
 */
class BinaryXML {
	private $xml;

	/**
	 * method generate XML document and save in a given path if path not given then send to consol.
	 *
	 * PARAMS
	 *	@$images an array of images with path so that method get images source
	 *  @ $savePath physical path to save XML document
	 *  @ $indentSource whther you want readable XML source on all in one line
	 *  @ $XMLVersion version of XML document
	 */
	public function generateBinaryXML($images, $savePath = 'php://output', $indentSource = false, $xmlVersion = '1.0') {
		$this->xml = new XMLWriter();
		$this->xml->openURI($savePath);
		if ($indentSource) {
			$this->xml->setIndent(true);
		}

		$this->xml->startDocument($xmlVersion);
		$this->xml->startElement('images');

		$totalImages = count($images);
		for($i=0; $i<$totalImages; $i++) {
			$this->addImageHash($images[$i]);
		}


		$this->xml->endElement();
		$this->xml->endDocument();
		return true;
	}


	public function parseXML($xmlFilePath, $outputDirectory) {
		$xml = simplexml_load_file($xmlFilePath);

		$imageName = '';
		foreach($xml as $node => $value) {
			if ($node == 'url') {
				$imageName = basename($value[0]);
			}
			else {
				$fp = fopen($outputDirectory . $imageName, 'w+');
				fputs($fp, base64_decode($value[0]));
				fclose($fp);
			}
		}
	}

	private function getImageSource($image) {
		return file_get_contents($image);
	}

	private function addImageHash($image) {
		$this->xml->startElement('url');
		$this->xml->Text($image);
		$this->xml->endElement();

		$this->xml->startElement('source');
		$this->xml->writeRaw(base64_encode($this->getImageSource($image)));
		$this->xml->endElement();
	}
}
?>
Return current item: Binary XML