Change Value of Current Child - SimpleXML PHP

The setup is quite simple. How do you use the children() iterating function of SimpleXML and then modify the value of the current node? Here's a scenario below:


I'm trying to use children() and then to assign to the current Child to change "Value" in all of the above nodes.

foreach ($parent->children() as $child){
  $child= "New Value"; // Proper way to access $child's value without overwriting the entire object???

Thanks in advance!

EDIT: I understand you can simply do the following:

$parent->Unit = "New Value"; 

I'm asking specifically in the case of using the children() method, how can you access the value of the current child object?


When a SimpleXMLElement represents a single element (rather than a collection of elements with the same name), index [0] can be used as a self-reference.

Writing to that self-reference uses the overloaded assignment that you can use in other contexts to set the text content of a node.

So the code you are looking for is as simple as:

foreach ($parent->children() as $child) {
    $child[0] = "New Value";

For case where you won't know the node names ahead of time you can try:

foreach ($parent->children() as $name => $child) {                                                                                                                                               
    $parent->{$name} = 'new value';

Need Your Help

What database privileges does a Wordpress Blog really need?

mysql wordpress privileges

I am setting up a few Wordpress blog sites. I have created a user in mysql that wordpress will use to access its database. The docs say to give this user all privileges on the database.

How to build a koolplot library using VC++ 2010

c++ visual-studio-2010 dll

I want to use simple plotting functions in my C++ code. Presently I am using Qt5 with VS2010 c++ compiler. I came across this library called koolplot. But I cannot buid it with VS2010 from its source

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.