ILIAS  eassessment Revision 61809
 All Data Structures Namespaces Files Functions Variables Groups Pages
XML_Util Class Reference
+ Collaboration diagram for XML_Util:

Static Public Member Functions

 apiVersion ()
 return API version
 replaceEntities ($string, $replaceEntities=XML_UTIL_ENTITIES_XML, $encoding= 'ISO-8859-1')
 replace XML entities
 reverseEntities ($string, $replaceEntities=XML_UTIL_ENTITIES_XML, $encoding= 'ISO-8859-1')
 reverse XML entities
 getXMLDeclaration ($version= '1.0', $encoding=null, $standalone=null)
 build an xml declaration
 getDocTypeDeclaration ($root, $uri=null, $internalDtd=null)
 build a document type declaration
 attributesToString ($attributes, $sort=true, $multiline=false, $indent= ' ', $linebreak="\n", $entities=XML_UTIL_ENTITIES_XML)
 create string representation of an attribute list
 collapseEmptyTags ($xml, $mode=XML_UTIL_COLLAPSE_ALL)
 Collapses empty tags.
 createTag ($qname, $attributes=array(), $content=null, $namespaceUri=null, $replaceEntities=XML_UTIL_REPLACE_ENTITIES, $multiline=false, $indent= '_auto', $linebreak="\n", $sortAttributes=true)
 create a tag
 createTagFromArray ($tag, $replaceEntities=XML_UTIL_REPLACE_ENTITIES, $multiline=false, $indent= '_auto', $linebreak="\n", $sortAttributes=true)
 create a tag from an array this method awaits an array in the following format
 createStartElement ($qname, $attributes=array(), $namespaceUri=null, $multiline=false, $indent= '_auto', $linebreak="\n", $sortAttributes=true)
 create a start element
 createEndElement ($qname)
 create an end element
 createComment ($content)
 create an XML comment
 createCDataSection ($data)
 create a CData section
 splitQualifiedName ($qname, $defaultNs=null)
 split qualified name and return namespace and local part
 isValidName ($string)
 check, whether string is valid XML name
 raiseError ($msg, $code)
 replacement for XML_Util::raiseError

Detailed Description

Definition at line 125 of file Util.php.

Member Function Documentation

XML_Util::apiVersion ( )
static

return API version

Returns
string $version API version public

Definition at line 134 of file Util.php.

{
return '1.1';
}
XML_Util::attributesToString (   $attributes,
  $sort = true,
  $multiline = false,
  $indent = '    ',
  $linebreak = "\n",
  $entities = XML_UTIL_ENTITIES_XML 
)
static

create string representation of an attribute list

require_once 'XML/Util.php';

// build an attribute string $att = array( 'foo' => 'bar', 'argh' => 'tomato' );

$attList = XML_Util::attributesToString($att);

Parameters
array$attributesattribute array
bool | array$sortsort attribute list alphabetically, may also be an assoc array containing the keys 'sort', 'multiline', 'indent', 'linebreak' and 'entities'
bool$multilineuse linebreaks, if more than one attribute is given
string$indentstring used for indentation of multiline attributes
string$linebreakstring used for linebreaks of multiline attributes
int$entitiessetting for entities in attribute values (one of XML_UTIL_ENTITIES_NONE, XML_UTIL_ENTITIES_XML, XML_UTIL_ENTITIES_XML_REQUIRED, XML_UTIL_ENTITIES_HTML)
Returns
string string representation of the attributes public replaceEntities() to replace XML entities in attribute values
Todo:
allow sort also to be an options array

Definition at line 383 of file Util.php.

References replaceEntities(), XML_UTIL_CDATA_SECTION, XML_UTIL_ENTITIES_NONE, and XML_UTIL_ENTITIES_XML.

Referenced by createStartElement(), createTagFromArray(), and getXMLDeclaration().

{
/*
* second parameter may be an array
*/
if (is_array($sort)) {
if (isset($sort['multiline'])) {
$multiline = $sort['multiline'];
}
if (isset($sort['indent'])) {
$indent = $sort['indent'];
}
if (isset($sort['linebreak'])) {
$multiline = $sort['linebreak'];
}
if (isset($sort['entities'])) {
$entities = $sort['entities'];
}
if (isset($sort['sort'])) {
$sort = $sort['sort'];
} else {
$sort = true;
}
}
$string = '';
if (is_array($attributes) && !empty($attributes)) {
if ($sort) {
ksort($attributes);
}
if ( !$multiline || count($attributes) == 1) {
foreach ($attributes as $key => $value) {
if ($entities != XML_UTIL_ENTITIES_NONE) {
if ($entities === XML_UTIL_CDATA_SECTION) {
$entities = XML_UTIL_ENTITIES_XML;
}
$value = XML_Util::replaceEntities($value, $entities);
}
$string .= ' ' . $key . '="' . $value . '"';
}
} else {
$first = true;
foreach ($attributes as $key => $value) {
if ($entities != XML_UTIL_ENTITIES_NONE) {
$value = XML_Util::replaceEntities($value, $entities);
}
if ($first) {
$string .= ' ' . $key . '="' . $value . '"';
$first = false;
} else {
$string .= $linebreak . $indent . $key . '="' . $value . '"';
}
}
}
}
return $string;
}

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

XML_Util::collapseEmptyTags (   $xml,
  $mode = XML_UTIL_COLLAPSE_ALL 
)
static

Collapses empty tags.

Parameters
string$xmlXML
int$modeWhether to collapse all empty tags (XML_UTIL_COLLAPSE_ALL) or only XHTML (XML_UTIL_COLLAPSE_XHTML_ONLY) ones.
Returns
string XML public
Todo:
PEAR CS - unable to avoid "space after open parens" error in the IF branch

Definition at line 454 of file Util.php.

References XML_UTIL_COLLAPSE_XHTML_ONLY.

{
return preg_replace(
'/<(area|base(?:font)?|br|col|frame|hr|img|input|isindex|link|meta|'
. 'param)([^>]*)><\/\\1>/s',
'<\\1\\2 />',
$xml);
} else {
return preg_replace('/<(\w+)([^>]*)><\/\\1>/s', '<\\1\\2 />', $xml);
}
}
XML_Util::createCDataSection (   $data)
static

create a CData section

require_once 'XML/Util.php';

// create a CData section $tag = XML_Util::createCDataSection('I am content.');

Parameters
string$datadata of the CData section
Returns
string CData section with content public

Definition at line 798 of file Util.php.

References $data.

Referenced by createTagFromArray().

{
return sprintf('<![CDATA[%s]]>',
preg_replace('/\]\]>/', ']]]]><![CDATA[>', strval($data)));
}

+ Here is the caller graph for this function:

XML_Util::createComment (   $content)
static

create an XML comment

require_once 'XML/Util.php';

// create an XML start element: $tag = XML_Util::createComment('I am a comment');

Parameters
string$contentcontent of the comment
Returns
string XML comment public

Definition at line 776 of file Util.php.

References $comment.

{
$comment = sprintf('<!-- %s -->', $content);
return $comment;
}
XML_Util::createEndElement (   $qname)
static

create an end element

require_once 'XML/Util.php';

// create an XML start element: $tag = XML_Util::createEndElement('myNs:myTag');

Parameters
string$qnamequalified tagname (including namespace)
Returns
string XML end element public
See Also
createStartElement(), createTag()

Definition at line 754 of file Util.php.

{
$element = sprintf('</%s>', $qname);
return $element;
}
XML_Util::createStartElement (   $qname,
  $attributes = array(),
  $namespaceUri = null,
  $multiline = false,
  $indent = '_auto',
  $linebreak = "\n",
  $sortAttributes = true 
)
static

create a start element

require_once 'XML/Util.php';

// create an XML start element: $tag = XML_Util::createStartElement('myNs:myTag', array('foo' => 'bar') ,'http://www.w3c.org/myNs#');

Parameters
string$qnamequalified tagname (including namespace)
array$attributesarray containg attributes
string$namespaceUriURI of the namespace
bool$multilinewhether to create a multiline tag where each attribute gets written to a single line
string$indentstring used to indent attributes (_auto indents attributes so they start at the same column)
string$linebreakstring used for linebreaks
bool$sortAttributesWhether to sort the attributes or not
Returns
string XML start element public
See Also
createEndElement(), createTag()

Definition at line 700 of file Util.php.

References attributesToString(), and splitQualifiedName().

{
// if no attributes hav been set, use empty attributes
if (!isset($attributes) || !is_array($attributes)) {
$attributes = array();
}
if ($namespaceUri != null) {
$parts = XML_Util::splitQualifiedName($qname);
}
// check for multiline attributes
if ($multiline === true) {
if ($indent === '_auto') {
$indent = str_repeat(' ', (strlen($qname)+2));
}
}
if ($namespaceUri != null) {
// is a namespace given
if (isset($parts['namespace']) && !empty($parts['namespace'])) {
$attributes['xmlns:' . $parts['namespace']] = $namespaceUri;
} else {
// define this Uri as the default namespace
$attributes['xmlns'] = $namespaceUri;
}
}
// create attribute list
$attList = XML_Util::attributesToString($attributes, $sortAttributes,
$multiline, $indent, $linebreak);
$element = sprintf('<%s%s>', $qname, $attList);
return $element;
}

+ Here is the call graph for this function:

XML_Util::createTag (   $qname,
  $attributes = array(),
  $content = null,
  $namespaceUri = null,
  $replaceEntities = XML_UTIL_REPLACE_ENTITIES,
  $multiline = false,
  $indent = '_auto',
  $linebreak = "\n",
  $sortAttributes = true 
)
static

create a tag

This method will call XML_Util::createTagFromArray(), which is more flexible.

require_once 'XML/Util.php';

// create an XML tag: $tag = XML_Util::createTag('myNs:myTag', array('foo' => 'bar'), 'This is inside the tag', 'http://www.w3c.org/myNs#');

Parameters
string$qnamequalified tagname (including namespace)
array$attributesarray containg attributes
mixed$contentthe content
string$namespaceUriURI of the namespace
int$replaceEntitieswhether to replace XML special chars in content, embedd it in a CData section or none of both
bool$multilinewhether to create a multiline tag where each attribute gets written to a single line
string$indentstring used to indent attributes (_auto indents attributes so they start at the same column)
string$linebreakstring used for linebreaks
bool$sortAttributesWhether to sort the attributes or not
Returns
string XML tag public
See Also
createTagFromArray() createTagFromArray() to create the tag

Definition at line 504 of file Util.php.

References createTagFromArray().

{
$tag = array(
'qname' => $qname,
'attributes' => $attributes
);
// add tag content
if ($content !== null) {
$tag['content'] = $content;
}
// add namespace Uri
if ($namespaceUri !== null) {
$tag['namespaceUri'] = $namespaceUri;
}
return XML_Util::createTagFromArray($tag, $replaceEntities, $multiline,
$indent, $linebreak, $sortAttributes);
}

+ Here is the call graph for this function:

XML_Util::createTagFromArray (   $tag,
  $replaceEntities = XML_UTIL_REPLACE_ENTITIES,
  $multiline = false,
  $indent = '_auto',
  $linebreak = "\n",
  $sortAttributes = true 
)
static

create a tag from an array this method awaits an array in the following format

array(
    // qualified name of the tag
    'qname' => $qname
    // namespace prefix (optional, if qname is specified or no namespace)
    'namespace' => $namespace
    // local part of the tagname (optional, if qname is specified)
    'localpart' => $localpart,
    // array containing all attributes (optional)
    'attributes' => array(),
    // tag content (optional)
    'content' => $content,
    // namespaceUri for the given namespace (optional)
    'namespaceUri' => $namespaceUri 
)

require_once 'XML/Util.php';

$tag = array( 'qname' => 'foo:bar', 'namespaceUri' => 'http://foo.com', 'attributes' => array('key' => 'value', 'argh' => 'fruit&vegetable'), 'content' => 'I\'m inside the tag', ); // creating a tag with qualified name and namespaceUri $string = XML_Util::createTagFromArray($tag);

Parameters
array$tagtag definition
int$replaceEntitieswhether to replace XML special chars in content, embedd it in a CData section or none of both
bool$multilinewhether to create a multiline tag where each attribute gets written to a single line
string$indentstring used to indent attributes (_auto indents attributes so they start at the same column)
string$linebreakstring used for linebreaks
bool$sortAttributesWhether to sort the attributes or not
Returns
string XML tag public
See Also
createTag() attributesToString() to serialize the attributes of the tag splitQualifiedName() to get local part and namespace of a qualified name createCDataSection() raiseError()

Definition at line 587 of file Util.php.

References attributesToString(), createCDataSection(), raiseError(), replaceEntities(), splitQualifiedName(), XML_UTIL_CDATA_SECTION, XML_UTIL_ENTITIES_NONE, XML_UTIL_ERROR_NO_TAG_NAME, and XML_UTIL_ERROR_NON_SCALAR_CONTENT.

Referenced by createTag().

{
if (isset($tag['content']) && !is_scalar($tag['content'])) {
return XML_Util::raiseError('Supplied non-scalar value as tag content',
}
if (!isset($tag['qname']) && !isset($tag['localPart'])) {
return XML_Util::raiseError('You must either supply a qualified name '
. '(qname) or local tag name (localPart).',
}
// if no attributes hav been set, use empty attributes
if (!isset($tag['attributes']) || !is_array($tag['attributes'])) {
$tag['attributes'] = array();
}
if (isset($tag['namespaces'])) {
foreach ($tag['namespaces'] as $ns => $uri) {
$tag['attributes']['xmlns:' . $ns] = $uri;
}
}
if (!isset($tag['qname'])) {
// qualified name is not given
// check for namespace
if (isset($tag['namespace']) && !empty($tag['namespace'])) {
$tag['qname'] = $tag['namespace'] . ':' . $tag['localPart'];
} else {
$tag['qname'] = $tag['localPart'];
}
} elseif (isset($tag['namespaceUri']) && !isset($tag['namespace'])) {
// namespace URI is set, but no namespace
$parts = XML_Util::splitQualifiedName($tag['qname']);
$tag['localPart'] = $parts['localPart'];
if (isset($parts['namespace'])) {
$tag['namespace'] = $parts['namespace'];
}
}
if (isset($tag['namespaceUri']) && !empty($tag['namespaceUri'])) {
// is a namespace given
if (isset($tag['namespace']) && !empty($tag['namespace'])) {
$tag['attributes']['xmlns:' . $tag['namespace']] =
$tag['namespaceUri'];
} else {
// define this Uri as the default namespace
$tag['attributes']['xmlns'] = $tag['namespaceUri'];
}
}
// check for multiline attributes
if ($multiline === true) {
if ($indent === '_auto') {
$indent = str_repeat(' ', (strlen($tag['qname'])+2));
}
}
// create attribute list
$attList = XML_Util::attributesToString($tag['attributes'],
$sortAttributes, $multiline, $indent, $linebreak, $replaceEntities);
if (!isset($tag['content']) || (string)$tag['content'] == '') {
$tag = sprintf('<%s%s />', $tag['qname'], $attList);
} else {
switch ($replaceEntities) {
break;
$tag['content'] = XML_Util::createCDataSection($tag['content']);
break;
default:
$tag['content'] = XML_Util::replaceEntities($tag['content'],
$replaceEntities);
break;
}
$tag = sprintf('<%s%s>%s</%s>', $tag['qname'], $attList, $tag['content'],
$tag['qname']);
}
return $tag;
}

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

XML_Util::getDocTypeDeclaration (   $root,
  $uri = null,
  $internalDtd = null 
)
static

build a document type declaration

require_once 'XML/Util.php';

// get a doctype declaration: $xmlDecl = XML_Util::getDocTypeDeclaration('rootTag','myDocType.dtd');

Parameters
string$rootname of the root tag
string$uriuri of the doctype definition (or array with uri and public id)
string$internalDtdinternal dtd entries
Returns
string doctype declaration public
Since
0.2

Definition at line 328 of file Util.php.

{
if (is_array($uri)) {
$ref = sprintf(' PUBLIC "%s" "%s"', $uri['id'], $uri['uri']);
} elseif (!empty($uri)) {
$ref = sprintf(' SYSTEM "%s"', $uri);
} else {
$ref = '';
}
if (empty($internalDtd)) {
return sprintf('<!DOCTYPE %s%s>', $root, $ref);
} else {
return sprintf("<!DOCTYPE %s%s [\n%s\n]>", $root, $ref, $internalDtd);
}
}
XML_Util::getXMLDeclaration (   $version = '1.0',
  $encoding = null,
  $standalone = null 
)
static

build an xml declaration

require_once 'XML/Util.php';

// get an XML declaration: $xmlDecl = XML_Util::getXMLDeclaration('1.0', 'UTF-8', true);

Parameters
string$versionxml version
string$encodingcharacter encoding
bool$standalonedocument is standalone (or not)
Returns
string xml declaration public attributesToString() to serialize the attributes of the XML declaration

Definition at line 289 of file Util.php.

References attributesToString().

{
$attributes = array(
'version' => $version,
);
// add encoding
if ($encoding !== null) {
$attributes['encoding'] = $encoding;
}
// add standalone, if specified
if ($standalone !== null) {
$attributes['standalone'] = $standalone ? 'yes' : 'no';
}
return sprintf('<?xml%s?>',
XML_Util::attributesToString($attributes, false));
}

+ Here is the call graph for this function:

XML_Util::isValidName (   $string)
static

check, whether string is valid XML name

XML names are used for tagname, attribute names and various other, lesser known entities.

An XML name may only consist of alphanumeric characters, dashes, undescores and periods, and has to start with a letter or an underscore.

require_once 'XML/Util.php';

// verify tag name $result = XML_Util::isValidName('invalidTag?'); if (is_a($result, 'PEAR_Error')) { print 'Invalid XML name: ' . $result->getMessage(); }

Parameters
string$stringstring that should be checked
Returns
mixed true, if string is a valid XML name, PEAR error otherwise public
Todo:

support for other charsets

PEAR CS - unable to avoid 85-char limit on second preg_match

Definition at line 871 of file Util.php.

References raiseError(), XML_UTIL_ERROR_INVALID_CHARS, and XML_UTIL_ERROR_INVALID_START.

{
// check for invalid chars
if (!preg_match('/^[[:alpha:]_]$/', $string{0})) {
return XML_Util::raiseError('XML names may only start with letter '
. 'or underscore', XML_UTIL_ERROR_INVALID_START);
}
// check for invalid chars
if (!preg_match('/^([[:alpha:]_]([[:alnum:]\-\.]*)?:)?[[:alpha:]_]([[:alnum:]\_\-\.]+)?$/',
$string)
) {
return XML_Util::raiseError('XML names may only contain alphanumeric '
. 'chars, period, hyphen, colon and underscores',
}
// XML name is valid
return true;
}

+ Here is the call graph for this function:

XML_Util::raiseError (   $msg,
  $code 
)
static

replacement for XML_Util::raiseError

Avoids the necessity to always require PEAR.php

Parameters
string$msgerror message
int$codeerror code
Returns
PEAR_Error public
Todo:
PEAR CS - should this use include_once instead?

Definition at line 905 of file Util.php.

Referenced by createTagFromArray(), and isValidName().

{
require_once 'PEAR.php';
return PEAR::raiseError($msg, $code);
}

+ Here is the caller graph for this function:

XML_Util::replaceEntities (   $string,
  $replaceEntities = XML_UTIL_ENTITIES_XML,
  $encoding = 'ISO-8859-1' 
)
static

replace XML entities

With the optional second parameter, you may select, which entities should be replaced.

require_once 'XML/Util.php';

// replace XML entites: $string = XML_Util::replaceEntities('This string contains < & >.');

With the optional third parameter, you may pass the character encoding require_once 'XML/Util.php';

// replace XML entites in UTF-8: $string = XML_Util::replaceEntities( 'This string contains < & > as well as ä, ö, ß, à and ê', XML_UTIL_ENTITIES_HTML, 'UTF-8' );

Parameters
string$stringstring where XML special chars should be replaced
int$replaceEntitiessetting for entities in attribute values (one of XML_UTIL_ENTITIES_XML, XML_UTIL_ENTITIES_XML_REQUIRED, XML_UTIL_ENTITIES_HTML)
string$encodingencoding value (if any)... must be a valid encoding as determined by the htmlentities() function
Returns
string string with replaced chars public
See Also
reverseEntities()

Definition at line 179 of file Util.php.

References XML_UTIL_ENTITIES_HTML, XML_UTIL_ENTITIES_XML, and XML_UTIL_ENTITIES_XML_REQUIRED.

Referenced by attributesToString(), and createTagFromArray().

{
switch ($replaceEntities) {
return strtr($string, array(
'&' => '&amp;',
'>' => '&gt;',
'<' => '&lt;',
'"' => '&quot;',
'\'' => '&apos;' ));
break;
return strtr($string, array(
'&' => '&amp;',
'<' => '&lt;',
'"' => '&quot;' ));
break;
return htmlentities($string, ENT_COMPAT, $encoding);
break;
}
return $string;
}

+ Here is the caller graph for this function:

XML_Util::reverseEntities (   $string,
  $replaceEntities = XML_UTIL_ENTITIES_XML,
  $encoding = 'ISO-8859-1' 
)
static

reverse XML entities

With the optional second parameter, you may select, which entities should be reversed.

require_once 'XML/Util.php';

// reverse XML entites: $string = XML_Util::reverseEntities('This string contains < & >.');

With the optional third parameter, you may pass the character encoding require_once 'XML/Util.php';

// reverse XML entites in UTF-8: $string = XML_Util::reverseEntities( 'This string contains < & > as well as' . ' ä, ö, ß, à and ê', XML_UTIL_ENTITIES_HTML, 'UTF-8' );

Parameters
string$stringstring where XML special chars should be replaced
int$replaceEntitiessetting for entities in attribute values (one of XML_UTIL_ENTITIES_XML, XML_UTIL_ENTITIES_XML_REQUIRED, XML_UTIL_ENTITIES_HTML)
string$encodingencoding value (if any)... must be a valid encoding as determined by the html_entity_decode() function
Returns
string string with replaced chars public
See Also
replaceEntities()

Definition at line 245 of file Util.php.

References XML_UTIL_ENTITIES_HTML, XML_UTIL_ENTITIES_XML, and XML_UTIL_ENTITIES_XML_REQUIRED.

{
switch ($replaceEntities) {
return strtr($string, array(
'&amp;' => '&',
'&gt;' => '>',
'&lt;' => '<',
'&quot;' => '"',
'&apos;' => '\'' ));
break;
return strtr($string, array(
'&amp;' => '&',
'&lt;' => '<',
'&quot;' => '"' ));
break;
return html_entity_decode($string, ENT_COMPAT, $encoding);
break;
}
return $string;
}
XML_Util::splitQualifiedName (   $qname,
  $defaultNs = null 
)
static

split qualified name and return namespace and local part

require_once 'XML/Util.php';

// split qualified tag $parts = XML_Util::splitQualifiedName('xslt:stylesheet'); the returned array will contain two elements:

array(
    'namespace' => 'xslt',
    'localPart' => 'stylesheet'
);
Parameters
string$qnamequalified tag name
string$defaultNsdefault namespace (optional)
Returns
array array containing namespace and local part public

Definition at line 829 of file Util.php.

Referenced by createStartElement(), and createTagFromArray().

{
if (strstr($qname, ':')) {
$tmp = explode(':', $qname);
return array(
'namespace' => $tmp[0],
'localPart' => $tmp[1]
);
}
return array(
'namespace' => $defaultNs,
'localPart' => $qname
);
}

+ Here is the caller graph for this function:


The documentation for this class was generated from the following file: