phpxmlsimplexmladdchild

PHP - Using special characters in XML tag


Hi I'm using PHP and I wrote an application that creates and fills a SimpleXMLObject with the results of a database query. The results are saved as tags. I accomplish this with

if (!isset($set->$parttemp)) {
$parttemp = "$parttemp &#40 $groupname &#41";
$set = $set->addChild($parttemp);
}

My problem is, I want to use special characters in the XML tags. With a bit of research I found out that you need to use the code of that character for example for "(" you need to write (

But if you want to use those codes within a tag you also need to replace the tags with that code. For example for <permission(s)/> I need to write &lt; permission &#40; s &#41; / &gt;

That would not be a big deal but the tags are set from the addChild operation so i can't manipulate them. Is there another solution?


Solution

  • Punctuation characters like "(" aren't valid in XML element or attribute names. Trying to escape them (for example as a decimal character reference &#40;) is no use - character references aren't recognized within the name.

    You'll have to find some application-level way of encoding the string as a valid name. For example, I've seen people use <permission_x28_s_x29_>.

    Usually, though, I would tend to prefer <element name="permissions(s)">.