views:

33

answers:

2

Good day,

I am having trouble modifying XML using SimpleXMLElement in PHP.

My XML structure is as below:

<chart caption='NULL' shownames='1' showvalues='0' decimals='2' numberPrefix='$' useRoundEdges='0' legendBorderAlpha='0' bgColor='FFFFFF' canvasBorderColor='A5A5A5' canvasBorderThickness='1' showToolTip='1'>
...
</chart>

How can I modify the attributes() on the root tag using SimpleXMLElement?

Thank you!

EDIT: Hmm... I found a way but I dont believe its very clean. I added a <root><chart ...>...</chart></root> tag wraping my XML data. And I finally added str_replace(array("<root>", "</root>"), "", $_RenderedXML->asXML()) to my code. Any idea that is.. "cleaner"?

A: 

It's works sort of like an associative array, once you access the chart object you want:

$sxe = new SimpleXMLElement($yourXML);
$sxe->chart[0]["caption"] = "A new value";

This will set the caption attribute of the first chart node to A new value.

SimpleCoder
Yep but my chart node is actually the root node. Your trick isnt working. Thank you though!
Cybrix
Try it now; you just need to select `root` before `chart` then
SimpleCoder
Who downvoted this answer?
SimpleCoder
If you are talking about my edit. Yes I can now use $_RenderedXML->chart->attributes()->caption = "something here"... but I'm looking for a "cleaner" solution. It wasn't me who downvoter you btw.
Cybrix
A: 

TO change the "shownames" attribute to (String) "2"

<?

$dom = simplexml_load_string("<chart caption='NULL' shownames='1' showvalues='0' decimals='2' numberPrefix='$' useRoundEdges='0' legendBorderAlpha='0' bgColor='FFFFFF' canvasBorderColor='A5A5A5' canvasBorderThickness='1' showToolTip='1'></chart>");
$dom['shownames'] = '2';
var_dump($dom);
Ollie
I dont know why this have been downvoted. But this work for me. I believe it was one technique I forgot to try.
Cybrix
Maybe because i had the sample XML inline with the code. which is kinda frowned upon. But i was too lazy to use DOMDocument to build up the XML. I never meant for this to be the actual code, but just enough to teach you how to do it so you can integrate into your code. Glad it helped :)
Ollie