shoprex-icon-big

Shoprex

Developer site for the Wordpress Plugin Shoprex

XML record with CDATA values and output


In an XML object, data that contains html codes must be placed in a <! [CDATA [* Text *]] block.

The SimpleXMLElement class is extended by the addCData method in the script. With a simple query text! = Strip_tags (text) it is decided whether the value has to be packed into a CDATA block.

The Ampersand (&) is also escaped in this script.

// Thanks to https://stackoverflow.com/a/6260295/8148987
// To add CDATA
class SimpleXMLExtended extends SimpleXMLElement {
	public function addCData( $cdata_text ) {
		$node = dom_import_simplexml( $this );
		$no   = $node->ownerDocument;
		$node->appendChild( $no->createCDATASection( $cdata_text ) );
	}
}

// Test Array
	$test = array(
		"field1" => "Simple String",
		"field2" => "<a href='#test'>String with HTML Code & Ampersand and casted &amp;</a>",
		"field3" => "< & &amp; && > Escape test",
		"field4" => "123"
	);

// Create XML Object
	$xml = new SimpleXMLExtended( "<dataset />" ); // Call of modified SimpleXMLElement

	$single = $xml->addChild( "single" );

	foreach ( $test as $colname => $value ) {

		if ( $value != strip_tags( $value ) ) // Check if String contains HTML Code, Thanks to https://stackoverflow.com/a/5732812/8148987
		{
			$single_child = $single->addChild( $colname );
			$single_child->addCData( $value );

		} else {
			$value_ampersand_escape = preg_replace("/&(?!.{2,4};)/", "&amp;", $value); // Escape Ampersands. Thanks to https://stackoverflow.com/a/24340260/8148987
			$single->addChild( $colname, $value_ampersand_escape );
		}
	}


// Display XML Code
	$dom                     = new DOMDocument( '1.0', "utf-8" );
	$dom->preserveWhiteSpace = false;
	$dom->formatOutput       = true;
	$dom->loadXML( $xml->asXML() );
	header( "Content-Type: application/xml; charset=utf-8" );

	echo $dom->saveXML();

Output:

// Output:
<?xml version="1.0"?>
<dataset>
  <single>
    <field1>Simple String</field1>
    <field2><![CDATA[<a href='#test'>String with HTML Code & Ampersand and casted &amp;</a>]]></field2>
    <field3>&lt; &amp; &amp; &amp;&amp; &gt; Escape test</field3>
    <field4>123</field4>
  </single>
</dataset>

Back

Leave a Reply

Your email address will not be published. Required fields are marked *

*
*
*