1

how to set text for a SimpleXMLElement in php?

user121196
  • 30,032
  • 57
  • 148
  • 198

3 Answers3

14

Let's say $node is an SimpleXMLElement. This code:

$node->{0} = "some string"

will result in an extra childNode in PHP 7, instead of setting the text content for $node. Use:

$node[0] = "some string"

instead.

ODaniel
  • 566
  • 4
  • 13
5

Did you look at the basic documentation examples?

From there:

include 'example.php';
$xml = new SimpleXMLElement($xmlstr);

$xml->movie[0]->characters->character[0]->name = 'Miss Coder';

echo $xml->asXML();
alxp
  • 6,153
  • 1
  • 22
  • 19
  • 1
    what if I need to set an element's text without knowing its parent? in other words, the element has already being created,perhaps with some attributes. – user121196 Jun 04 '10 at 00:21
  • For that you use the XPath syntax to make a query like: foreach ($xml->xpath('//character') as $character) { echo $character->name, 'played by ', $character->actor, '
    '; }
    – alxp Jun 04 '10 at 05:25
2
$xml = SimpleXMLElement('<a><b><c></c></b></a>');
$foundNodes = $xml->xpath('//c');
$foundNode = $foundNodes[0];
$foundNode->{0} = "This text will be put inside of c tag.";

$xml->asXML(); 
// will output <a><b><c>This text will be put inside of c tag.</c></b></a>

More on my search of this answer here:

Community
  • 1
  • 1
Kamil Szot
  • 17,436
  • 6
  • 62
  • 65