简体   繁体   中英

Simple variable question in PHP and XML

I would like to add a variable ( $var ) inside the following code but I am having error...

$employee = $xml->addChild('XXXXXXX');
$employee->addChild('XXXXX', 'XXXXXX');

Any help would be great. In addition how can i modify the first line so that I can add an attribute to it? For example <book ID="XXXX">

Thank you!

addChild takes a DOMNode as its argument, not text strings. You need to create the nodes and append them... for example:

//assuming $xml is a DOMDoucment

// <employee>XXX</employee>
$employee = $xml->createElement('employee', 'XXX');

// create an attribute node and a text nod to use for its value
$idNode = $xml->createAttribute('id');
$idValue = $xml->createTextNode('some-id');

// set the value of the attribute node
$idNode->appendChild($idValue);

// add the attribute to the element
$employee->appendChild($idNode);

// or more easily add an attribute
$employee->setAttribute('another', 'some-value');

// append the element to the document
$xml->appendChild($employee);

// final result:
// <root><employee id="some-id" another="some-value">XXX</employee></root>

这会将属性添加到XML元素:

    $xml->addAttribute("id","1234");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM