Change Value of Current Child - SimpleXML PHP

ぐ巨炮叔叔 提交于 2019-12-11 13:03:00

问题


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:

<Ad>
  <Unit>Value</Unit>
  <Size>Value</Size>
  <Time>Value</Time>
</Ad>

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?


回答1:


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";
}



回答2:


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';
}


来源:https://stackoverflow.com/questions/32111703/change-value-of-current-child-simplexml-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!