XML decoding Planet request from transaction processor data - PHP Online
Form of PHP Sandbox
Enter Your PHP code here for testing/debugging in the Online PHP Sandbox. As in the usual PHP files, you can also add HTML, but do not forget to add the tag <?php
in the places where the PHP script should be executed.
Result of php executing
Full code of XML decoding Planet request from transaction processor data.php
- <?php
- $processor_data = <<<EOS
- <?xml version="1.0" encoding="UTF-8"?>
- <mysql type="array"><auth type="array"><send type="string"><?xml version="1.0" encoding="UTF-8"?><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"><soapenv:Header/><soapenv:Body><AuthorizationMCP xmlns="http://www.planetpayment.net"><req><AccessInfo><User>321400000002</User><Password>**************</Password><TerminalID>90000101</TerminalID><ApplicationID>Cardstream v3</ApplicationID><GatewayTransactionId>10017683</GatewayTransactionId></AccessInfo><CardInfo><CardAccountNumber>****************</CardAccountNumber><CardExpirationMonth>12</CardExpirationMonth><CardExpirationYear>19</CardExpirationYear><StartDateMonth>01</StartDateMonth><StartDateYear>19</StartDateYear><CardVerificationNumber>***</CardVerificationNumber><POSEntryMode>010</POSEntryMode><POSConditionCode>59</POSConditionCode><POSTerminalCapability>0</POSTerminalCapability><CardholderIdMethod>4</CardholderIdMethod><ECI>7</ECI><ECIDirectMktgOrderNumber>10017683</ECIDirectMktgOrderNumber><PartialAuthorization>0</PartialAuthorization><TransactionInitiatedBy>2</TransactionInitiatedBy><!-- Not supported<CardVerificationIndicator/><Track1/><Track2/><Track3/><CustomerDataStoreAccessInfo/><BuyVoiceAccessInfo/><RecurringTransaction/><PCard/><AdditionalMarketData/><CardInfoEnv/><BillPayment/><DebitRequest/><InternetAirlineCustomer/><CardType/><InstallmentPayment1/><InstallmentPayment2/>--><FinalAuthIndicator>P</FinalAuthIndicator></CardInfo><TransactionInfo><RequestIdentifier>5d655400b7119</RequestIdentifier><TransactionAmount>780</TransactionAmount><TransactionCurrencyCode>826</TransactionCurrencyCode></TransactionInfo><BillingAndShippingInfo><BillingName>Nick Turner</BillingName><BillingAddress>Flat 6, Primrose Rise347 Lavender Road</BillingAddress><BillingCity>Northampton</BillingCity><BillingState>Northamptonshire</BillingState><BillingPostalCode>NN17 8YG</BillingPostalCode><BillingCountry>GB</BillingCountry><BillingEmail>[email protected]</BillingEmail><ShippingName>Operations Manager</ShippingName><ShippingAddress>3705 Bank of America Tower12 Harcourt Road</ShippingAddress><ShippingCity>Hong Kong</ShippingCity><ShippingState>Central</ShippingState><ShippingPostalCode>HK 01</ShippingPostalCode><ShippingCountry>HK</ShippingCountry><ShippingEmail>[email protected]</ShippingEmail></BillingAndShippingInfo><RequestAdditionalResponseData><TransactionDetailExFlag>Y</TransactionDetailExFlag></RequestAdditionalResponseData><MCPInfo><MCPAmount>780</MCPAmount><MCPCurrencyCode>826</MCPCurrencyCode></MCPInfo></req></AuthorizationMCP></soapenv:Body></soapenv:Envelope></send><recv type="string"><?xml version="1.0"?>
- <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"><s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><AuthorizationMCPResponse xmlns="http://www.planetpayment.net"><AuthorizationMCPResult><ResponseInfo><ResponseDetail><ResponseCode>00</ResponseCode><ResponseMessage>Approved</ResponseMessage><LocalTransactionDate>08/27/2019</LocalTransactionDate><LocalTransactionTime>12:02:07:0811</LocalTransactionTime><RequestIdentifier>5d655400b7119</RequestIdentifier><RetrievalReferenceNumber>923941557411</RetrievalReferenceNumber><ProcessingTime>00:00:156</ProcessingTime></ResponseDetail><ResponseTransactionDetail><AVSResponseCode>Y</AVSResponseCode><CVVResponseCode>M</CVVResponseCode><AuthorizationSourceCode>5</AuthorizationSourceCode><AuthorizationNumber>16875A</AuthorizationNumber><CardAccountNumber>****************</CardAccountNumber><TransactionAmount>906</TransactionAmount><TransactionCurrencyCode>840</TransactionCurrencyCode><CardholderBillingTransactionAmount>780</CardholderBillingTransactionAmount><CardholderBillingTransactionCurrencyCode>826</CardholderBillingTransactionCurrencyCode></ResponseTransactionDetail><EMVResponseData/><Planet3DSecureResponseData><ECI>7</ECI></Planet3DSecureResponseData></ResponseInfo><ResponseMCPInfo><MCPAmount>780</MCPAmount><MCPCurrencyCode>826</MCPCurrencyCode><MCPTransactionConversionRate>1161257</MCPTransactionConversionRate><MCPTransactionConversionExponent>6</MCPTransactionConversionExponent><MCPTransactionConvertedAmount>906</MCPTransactionConvertedAmount><MCPLocalTransactionDate>08/27/2019</MCPLocalTransactionDate><MCPLocalTransactionTime>12:02:07:0811</MCPLocalTransactionTime></ResponseMCPInfo></AuthorizationMCPResult></AuthorizationMCPResponse></s:Body></s:Envelope>
- </recv></auth><RequestIdentifier type="string">5d655400b7119</RequestIdentifier><RetrievalReferenceNumber type="string">923941557411</RetrievalReferenceNumber><processorXref type="string">923941557411</processorXref><void type="array"><send type="string"><?xml version="1.0" encoding="UTF-8"?><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"><soapenv:Header/><soapenv:Body><VoidTransaction xmlns="http://www.planetpayment.net"><req><AccessInfo><User>321400000002</User><Password>**************</Password><TerminalID>90000101</TerminalID><ApplicationID>Cardstream v3</ApplicationID><GatewayTransactionId>10017683</GatewayTransactionId></AccessInfo><RequestIdentifier>5d655400b7119</RequestIdentifier><RetrievalReferenceNumber>923941557411</RetrievalReferenceNumber></req></VoidTransaction></soapenv:Body></soapenv:Envelope></send><recv type="string"><?xml version="1.0"?>
- <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"><s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><VoidTransactionResponse xmlns="http://www.planetpayment.net"><VoidTransactionResult><ResponseDetail><ResponseCode>00</ResponseCode><ResponseMessage>Approved</ResponseMessage><LocalTransactionDate>08/27/2019</LocalTransactionDate><LocalTransactionTime>12:02:09:0390</LocalTransactionTime><RequestIdentifier>5d655400b7119</RequestIdentifier><RetrievalReferenceNumber>923941557411</RetrievalReferenceNumber><ProcessingTime>00:00:218</ProcessingTime></ResponseDetail><ResponseVoidTransactionDetail><CardAccountNumber>****************</CardAccountNumber><TransactionAmount>906</TransactionAmount><TransactionCurrencyCode>840</TransactionCurrencyCode><OriginalRetrievalReferenceNumber>923941557411</OriginalRetrievalReferenceNumber></ResponseVoidTransactionDetail></VoidTransactionResult></VoidTransactionResponse></s:Body></s:Envelope>
- </recv></void><_extendedData type="array"><riskCheckEnabled type="string">N</riskCheckEnabled><surchargeEnabled type="string">N</surchargeEnabled><requestMerchantID type="string">110053</requestMerchantID><processMerchantID type="string">110053</processMerchantID><paymentMethod type="string">card</paymentMethod><merchantType type="string">iusdfiksdfhnfvhvgedj</merchantType><merchantOriginalOrderRef type="string">ksdaskdjhaksjdh</merchantOriginalOrderRef><shippingTaxReason type="string">VAT</shippingTaxReason><shippingDiscountAmount type="integer">100</shippingDiscountAmount><shippingDiscountReason type="string">Frequent Flyer</shippingDiscountReason><facilitatorName type="string">ASDA STORES</facilitatorName><facilitatorID type="string">9876543210</facilitatorID><subMerchantID type="string">0123456789</subMerchantID><surchargeRequired type="string">N</surchargeRequired><cardType type="string">Visa Credit</cardType><cardTypeCode type="string">VC</cardTypeCode><cardScheme type="string">Visa</cardScheme><cardSchemeCode type="string">VC</cardSchemeCode><cardIssuer type="string">Unknown</cardIssuer><cardIssuerCountry type="string">Unknown</cardIssuerCountry><cardIssuerCountryCode type="string">XXX</cardIssuerCountryCode><cardProductCode type="string">0</cardProductCode><cardFlags type="integer">6225924</cardFlags><cardNumberValid type="string">Y</cardNumberValid><cancelReason type="string">Automatic authorisation void, preauth only</cancelReason><vcsResponseCode type="integer">0</vcsResponseCode><vcsResponseMessage type="string">Success - no velocity check rules applied</vcsResponseMessage><acquirerResponseCode type="string">00</acquirerResponseCode><acquirerResponseMessage type="string">Approved</acquirerResponseMessage></_extendedData></mysql>
- EOS;
- $data = P3Xml::decode($processor_data);
- //echo 'Send: ' . var_export($data['auth']['send'], true) . PHP_EOL;
- /////////////////////////////////////////////////////////////////////////////////////////////////////////
- // Example 1: Preserving namespaces
- /////////////////////////////////////////////////////////////////////////////////////////////////////////
- echo 'Namespaces preserved' . PHP_EOL;
- echo '~~~~~~~~~~~~~~~~~~~~' . PHP_EOL;
- $xml = simplexml_load_string($data['auth']['send']);
- // Or if you think they may be syntax errors (unlikely in this case)
- /*
- if (($xml = P3Xml::load($data['auth']['send'], 'SimpleXmlElement', null, $errmsg)) === false) {
- die('error: ' . var_export($errmsg, true). PHP_EOL);
- }
- */
- //echo 'XML: ' . var_export($xml->asXml(), true) . PHP_EOL;
- // Access part of Planet request
- echo 'User: ' . (string)$xml->children('http://schemas.xmlsoap.org/soap/envelope/')->Body->children('http://www.planetpayment.net')->AuthorizationMCP->req->AccessInfo->User . PHP_EOL;
- // Or using Xpath
- $xml->registerXPathNamespace('s', 'http://schemas.xmlsoap.org/soap/envelope/');
- $xml->registerXPathNamespace('p', 'http://www.planetpayment.net');
- echo 'User: ' . (string)$xml->xpath('/s:Envelope/s:Body/p:AuthorizationMCP/p:req/p:AccessInfo/p:User')[0] . PHP_EOL;
- unset($xml);
- echo PHP_EOL . PHP_EOL;
- /////////////////////////////////////////////////////////////////////////////////////////////////////////
- // Example 2: Stripping namespaces
- /////////////////////////////////////////////////////////////////////////////////////////////////////////
- echo 'Namespaces stripped' . PHP_EOL;
- echo '~~~~~~~~~~~~~~~~~~~' . PHP_EOL;
- $send = preg_replace('%(</?)(?:[\\w-]+:)([\\w-]+)%', '\\1\\2', $data['auth']['send']);
- $send = preg_replace('%xmlns(?::[\\w-]+)?="[^"]+"%', '', $send);
- //var_export($send);
- $xml = simplexml_load_string($send);
- // Or if you think they may be syntax errors (unlikely in this case)
- /*
- if (($xml = P3Xml::load($data['auth']['send'], 'SimpleXmlElement', null, $errmsg)) === false) {
- die('error: ' . var_export($errmsg, true). PHP_EOL);
- }
- */
- //echo 'XML: ' . var_export($xml->asXml(), true) . PHP_EOL;
- // Access part of Planet request
- echo 'User: ' . (string)$xml->Body->AuthorizationMCP->req->AccessInfo->User . PHP_EOL;
- // Or using Xpath
- echo 'User: ' . (string)$xml->xpath('/Envelope/Body/AuthorizationMCP/req/AccessInfo/User')[0] . PHP_EOL;
- // Slow convert to an array (not possible if namespaces are presevered)
- echo 'array: ' . var_export(P3Xml::decode($send), true) . PHP_EOL;
- // Quick convert to an array (not possible if namespaces are presevered)
- echo 'array: ' . var_export(json_decode(json_encode($xml), true), true) . PHP_EOL;
- /**
- *
- * PLATFORM 3 - XML Utilities
- * ==========================
- *
- * This class provides various static methods for handling XML formatted
- * strings and libXml based objects.
- *
- * @package Cardstream
- * @subpackage Shared/Classes
- * @copyright Copyright (c) 2011 - Cardstream Ltd.
- * @author Nick Turner <[email protected]>
- * @link http://www.cardstream.com
- * @version $Id$
- */
- /**
- * XML Utilities.
- *
- * This is a small static class containing methods used to manipulate XML
- * formatted strings and objects.
- *
- * @author Nick Turner <[email protected]>
- * @static
- * @cs ignore NoNamespace
- */
- class P3Xml {
- /**
- * Convert all applicable characters to XML entities.
- *
- * This is the equivalent to the PHP {@link htmlentities()} but for XML.
- *
- * @param string $str string to convert
- * @return string converted string
- */
- static public function entities($str) {
- static $tr = array(
- '&#' => '&#',
- '&' => '&',
- '\'' => ''',
- '<' => '<',
- '>' => '>',
- '"' => '"',
- );
- return strtr($str, $tr);
- }
- /**
- * Convert associative array to XML attribute list.
- *
- * The array keys are expected to be valid values for use as XML
- * attribute names, the values will be enclosed in double quotes and
- * escaped using {@link P3Xml::entities()}.
- *
- * For example:
- * <pre>
- * $a = P3Xml::attrs(array('a' => '<apple>', 'b' => '<banana>'));
- * $a === 'a="<apple>" b="<banana>"';
- * </pre>
- *
- * @param array $attrs attributes to convert
- * @return string converted string
- */
- static public function attrs(array $attrs) {
- return join(' ', array_map(function($k, $v) { return P3Xml::entities($k) . '="' . P3Xml::entities($v) . '"'; }, array_keys($attrs), array_values($attrs)));
- }
- /**
- * Load an XML string.
- *
- * This will load an XML string into a libXml DOM which can then be
- * accessed via a {@link DOMDocument} or a {@link SimpleXmlElement}
- * which will be returned.
- *
- * The method will create an object of $class, which must be derived from
- * either the SimpleXmlElement class otherwise the method will throw an
- * InvalidArgumentException.
- *
- * The created object is then used to load the XML string an if the load
- * is successful then the method returns the object otherwise it deletes
- * it and returns null, placing the last error message in $errmsg.
- *
- * @param string $str XML formatted string to load
- * @param string $class name of class to load into
- * @param array $options bitwise OR of the libxml options
- * @param string $errmsg string to return any error message
- * @return object object of class $class (or null)
- * @throws InvalidArgumentException
- */
- static public function load($str, $class = 'SimpleXmlElement', $options = null, &$errmsg = null) {
- libxml_clear_errors();
- libxml_use_internal_errors(true);
- if (!$class || strcasecmp($class, 'SimpleXmlElement') === 0 || is_subclass_of($class, 'SimpleXmlElement')) {
- $ret = simplexml_load_string($str, $class, $options);
- } else if (strcasecmp($class, 'DOMDocument') === 0 || is_subclass_of($class, 'DOMDocument')) {
- $ret = new $class();
- if (!$ret->loadXml($str, $options)) {
- unset($ret);
- $ret = false;
- }
- } else {
- throw new InvalidArgumentException('Class must be or derived from either SimpleXmlElement or DOMDocument');
- }
- if ($ret === false) {
- if (($e = libxml_get_last_error())) {
- $errmsg = trim($e->message) . " at line {$e->line}.{$e->column}";
- } else {
- $errmsg = 'Unknown error';
- }
- }
- return $ret;
- }
- /**
- * Return an XML node or attribute object identified by a given Xpath
- * expression.
- *
- * This evaluate the $xpath Xpath expression to determine a node in the $xml
- * libXml DOM. If the expression matches more than one node then the first
- * is used.
- *
- * If required the $attr attribute is located on the found node and it is
- * returned instead of the node.
- *
- * The libXml DOM must be provided using an object which must be derived
- * from either the SimpleXmlElement class or the DOMDocument class,
- * otherwise the method will throw an InvalidArgumentException.
- *
- * If the expression doesn't match any XML node or if the node doesn't
- * have any required attribute then the method returns null.
- *
- * @param object $xml libXML DOM object
- * @param string $xpath Xpath expression
- * @param string $attr attribute name
- * @return object node or attribute object (or null)
- * @throws InvalidArgumentException
- */
- static public function item($xml, $xpath, $attr = null) {
- if (is_a($xml, 'SimpleXmlElement')) {
- $nodes = $xml->xpath($xpath);
- $ret = (isset($nodes[0]) ? ($attr ? ((isset($nodes[0][$attr])) ? $nodes[0][$attr] : null) : $nodes[0]) : null);
- } else if (is_a($xml, 'DOMNode')) {
- $x = new DOMXPath((is_a($xml, 'DOMDocument') ? $xml : $xml->ownerDocument));
- $nodes = $x->query($xpath, $xml);
- $ret = (($n = $nodes->item(0)) ? ($attr ? ($n->hasAttribute($attr) ? $n->getAttributeNode($attr) : null) : $n) : null);
- } else {
- throw new InvalidArgumentException('XML root must be either a SimpleXmlElement or a DOMNode');
- }
- return $ret;
- }
- /**
- * Copy an XML node to a new parent node.
- *
- * This will clone the given node and add it as a new child of the given
- * parent. The node and parent do not have to existing in the same DOM.
- *
- * The parent and node objects must both be derived from either the
- * SimpleXmlElement class or the DOMDocument class, otherwise the method
- * will throw an InvalidArgumentException.
- *
- * @param object $parent parent to add copy to
- * @param object $node node to copy
- * @return object new child node of parent
- * @throws InvalidArgumentException
- */
- static public function copy($parent, $node) {
- if (is_a($parent, 'SimpleXmlElement') && is_a($node, 'SimpleXmlElement')) {
- $parent = dom_import_simplexml($parent);
- $node = dom_import_simplexml($node);
- return simplexml_import_dom(self::copy($parent, $node));
- } else if (is_a($parent, 'DOMNode') && is_a($node, 'DOMNode')) {
- if ($parent->ownerDocument === $node->ownerDocument) {
- return $parent->appendChild($node->cloneNode(true));
- } else {
- return $parent->appendChild($parent->ownerDocument->importNode($node, true));
- }
- } else {
- throw new InvalidArgumentException('Node must be either a SimpleXmlElement or a DOMNode');
- }
- }
- /**
- * Decode an XML encoded string into a PHP variable.
- *
- * This take a XML encoded string as and return a native PHP variable.
- * It is for XML what {@link json_decode()} is for JSON.
- *
- * The XML encoded string must use plain XML text nodes with no attributes
- * etc., such as is created by the {@link encode()} method of this class.
- *
- * The $xml parameter can either be a string or a libXml object derived from
- * either the SimpleXmlElement class or the DOMDocument class, otherwise the
- * method will throw an InvalidArgumentException.
- *
- * @param mixed $xml xml encoded string or libXml object
- * @return mixed PHP variable (or null)
- * @throws InvalidArgumentException
- */
- static public function decode($xml) {
- libxml_clear_errors();
- libxml_use_internal_errors(true);
- if (is_string($xml)) {
- $xml = simplexml_load_string($xml);
- return self::decode($xml);
- } else if (is_a($xml, 'DOMNode')) {
- $xml = simplexml_import_dom($xml);
- return self::decode($xml);
- } else if (!is_a($xml, 'SimpleXmlElement')) {
- throw new InvalidArgumentException('Argument must be either an XML formatted string, an SimpleXmlElement or a DOMNode');
- }
- if ($xml->count()) {
- $ret = array();
- foreach ($xml as $k => $v) {
- $n = (isset($v['id']) ? (ctype_digit($v['id']) ? (int)$v['id'] : (string)$v['id']) : $k);
- $ret[$n] = self::decode($v);
- }
- } else {
- $ret = (string)$xml;
- }
- if (isset($xml['type'])) {
- $type = (string)$xml['type'];
- if (($type === 'array' || $type === 'object') && $ret === '') {
- $ret = null;
- }
- if ($type === 'object' && isset($xml['class']) && ($class = (string)$xml['class']) !== 'stdClass') {
- if (!method_exists($class, '__set_state')) {
- throw new RuntimeException('Cannot decode class: ' . $class);
- }
- $ret = $class::__set_state((array)$ret);
- } else if ($type === 'boolean') {
- $ret = ($ret === 'TRUE');
- } else if ($type === 'string' && isset($xml['escaped'])) {
- if ((string)$xml['escaped'] !== 'cs') {
- throw new RuntimeException('Unknown string escaping type: ' . $xml['escaped']);
- }
- $ret = ($ret === '' ? '' : stripcslashes($ret));
- } else {
- settype($ret, $type);
- }
- }
- return $ret;
- }
- /**
- * Encode a PHP variable as XML encoded string.
- *
- * This takes a native PHP variable and returns an XML encoded string.
- * It is for XML what {@link json_encode()} is for JSON.
- *
- * The PHP variable must be a scalar variable or array of scalar variables,
- * otherwise the method will throw an InvalidArgumentException.
- *
- * The $output parameter determines the return type and can be either
- * 'string', 'SimpleXmlElement' or 'DOMNode', otherwise the method will
- * throw an InvalidArgumentException.
- *
- * @param string $val PHP value to encode
- * @param string $output output type
- * @param string $charset xml character set
- * @param string $root root tag name
- * @return mixed PHP variable (or null)
- * @throws InvalidArgumentException
- */
- static public function encode($val, $output = 'string', $charset = 'UTF-8', $root = 'p3xml') {
- static $ctl = "\000\001\002\003\004\005\006\007\010\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037";
- static $ctlbs = "\000\001\002\003\004\005\006\007\010\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037\\";
- if (is_a($output, 'SimpleXmlElement')) {
- $node = $output;
- $node['type'] = $type = gettype($val);
- if ($type === 'array' || $type === 'object') {
- $tag = $node->getName();
- if ($type === 'object') {
- $node['class'] = get_class($val);
- }
- $i = ($tag === $root ? 'item' : $tag);
- foreach ((array)$val as $k => $v) {
- if (is_int($k) || !preg_match('/^[_A-Za-z][_A-Za-z0-9]*$/', $k)) {
- $child = $node->addChild($i);
- $child['id'] = $k;
- } else {
- $child = $node->addChild($k);
- }
- self::encode($v, $child, $charset, $root);
- }
- } else if ($type === 'boolean') {
- $node[0] = ($val ? 'TRUE' : 'FALSE');
- } else if ($type === 'integer' || $type === 'double') {
- $node[0] = $val;
- } else if ($type === 'string') {
- // Have to escape control characters until we can use XML v1.1
- if ($val === '') {
- // Don't add any node content
- } else if (strcspn($val, $ctl) === strlen($val)) {
- $node[0] = $val;
- } else {
- $node[0] = addcslashes($val, $ctlbs);
- $node['escaped'] = 'cs';
- }
- } else if ($val === null) {
- // Don't add any node content
- } else {
- throw new InvalidArgumentException('Unsupported data type: ' . gettype($val));
- }
- } else {
- $xml = new SimpleXmlElement('<?xml version="1.0" encoding="' . self::entities($charset) . '"?' . '><' . $root . '/>');
- self::encode($val, $xml, $charset, $root);
- switch ($output) {
- case 'SimpleXmlElement':
- return $xml;
- case 'DOMNode':
- return dom_import_simplexml($xml);
- default:
- return trim($xml->asXml());
- }
- }
- }
- /**
- * Format XML into a string.
- *
- * This will take a XML encoded string and return it nicely formatted with
- * indentation etc.
- *
- * The $xml parameter can either be a string or a libXml object derived from
- * either the SimpleXmlElement class or the DOMDocument class, otherwise the
- * method will throw an InvalidArgumentException.
- *
- * If $xml is not a valid XML formatted string then it will be returned
- * unformatted.
- *
- * @param mixed $xml xml encoded string or libXml object
- * @return mixed formated string (or original)
- * @throws InvalidArgumentException
- */
- static public function format($xml) {
- libxml_clear_errors();
- libxml_use_internal_errors(true);
- if (is_string($xml)) {
- $doc = new DOMDocument();
- if (!$doc->loadXml($xml)) {
- return $xml;
- }
- } else if (is_a($xml, 'SimpleXmlElement')) {
- $doc = new DOMDocument();
- $doc->importNode(dom_import_simplexml($xml), true);
- } else if (is_a($xml, 'DOMNode')) {
- $doc = $xml->ownerDocument;
- } else {
- throw new InvalidArgumentException('Argument must be either an XML formatted string, an SimpleXmlElement or a DOMNode');
- }
- $doc->preserveWhiteSpace = false;
- $doc->formatOutput = true;
- return $doc->saveXml();
- }
- }
- /* vim: set noexpandtab tabstop=4 shiftwidth=4: */