2

Given this XML/XHTML snippet:

<h1>
    <zuq:data name="siteHeader" />
</h1>

<h2>
    <zuq:data name="pageHeaderName" />
    <span>&mdash;</span>
    <zuq:data name="pageHeaderTitle" />
</h2>

I've used SimpleXML's XPath method to round up all top-level nodes in the zuq namespace. Since the array elements of the xpath() method are pseudo references to the SimpleXML object tree nodes, I figured manipulation would be easy. However, I cannot figure out how to replace a given element node with a text node. How could I, for example, replace <zuq:data name="siteHeader" /> with the text My Site Header.

I've considered simply targeting the parent node and modifying it's contents as could work with the first block (<h1>), but I don't see that working given the case of my second block (<h2>).

Is there an easy way to replace a given element node with a text node via SimpleXML in PHP?

2 Answers 2

1

as far as i know, simplexml doesn't have the capability to remove or replace nodes. it's more for reading, creating, and non-structure related edits. you will have to use a DOM XML object to fully replace nodes. it's sort of like a more complex version of simplexml. read about it here:

http://www.php.net/manual/en/book.domxml.php

Sign up to request clarification or add additional context in comments.

3 Comments

Alright, thanks dqhendricks. According to PHP docs, it appears DOM XML has been removed from the PHP core as of 5.0.0, and moved to the PECL. The other DOM classes should be more comprehensive, no?
it seems you are right. in that case, reference: php.net/manual/en/book.dom.php
Thanks again dqhendricks; DOM seems to provide the necessary functionality, albeit with much more lexical overhead.
1

Quickly looking at the documentation I was not able to find a simple way either. I would try to just iterate over the original xml doc and copy each element to a new xml doc, modifying them as necessary.

3 Comments

Hmm, that will certainly prove cumbersome. Since I haven't gone and written a whole ton of logic surrounding the use of SimpleXML, would it be advisable to explore other options for PHP XML document traversal/manipulation?
You might want to look into xsl transformations, it's really powerful and your xpath stuff fits right in there: php.net/manual/en/book.xsl.php
Thanks Abdullah Jibaly; XSLT is likely something I'll need for another aspect of the project, however it seems DOM fits the case. It simply offers more programmatic features that I require.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.