I have a problem with writing a specific string to a XML file.
The XML structure is this:
<ePrekrsaji>
<time>
<shift hours="48"/>
</time>
</ePrekrsaji>
The code I use doesnt seem to work:
$my_file = "hours.xml";
$hours = 5
$xml = new DOMDocument();
$xml->load($my_file);
$xml_hours = $xml->createElement($hours);
$nodes = $xml->getElementsByTagName('shift ') ;
if ($nodes->length > 0) {
$xml->appendChild( $xml_hours );
}
$xml->save($my_file);
ERROR I GET Fatal error: Uncaught exception 'DOMException' with message 'Invalid Character Error' in /var/www/WebDiP/2013_projekti/WebDiP2013_031/skripte/vrijeme.php:17 Stack trace: #0 /var/www/WebDiP/2013_projekti/WebDiP2013_031/skripte/vrijeme.php(17): DOMDocument->createElement('') #1 {main} thrown in /var/www/WebDiP/2013_projekti/WebDiP2013_031/skripte/vrijeme.php on line 17
How to write to this specfic node?
I want the end result to be:
<ePrekrsaji>
<time>
<shift hours="5"/>
</time>
</ePrekrsaji>
You tried to create an element <5 />
, are you sure it's the correct element name?
I think you wanted to make st. like this:
$xml_hours = $xml->createElement('hours', $hours);
I post you a solution with SimpleXML
class, so we getting the data from file using file_get_contents
then we edit the attribute hours
of shift
element, then we save the contents with file_put_contents
.
$file = "hours.xml";
$xml_data = file_get_contents($file);
$xml = new SimpleXMLElement($xml_data);
$xml->time->shift->attributes()->hours = 5;
file_put_contents($file, $xml->asXML());
Here's a corrected version of your code. You just need to get the first shift element and then set it's attribute.
$file = "hours.xml";
$hours = 6;
$xml = new DOMDocument();
$xml->load($file);
// get list of all shift elements
$nodes = $xml->getElementsByTagName('shift');
// get first shift element
$xmlShift = $nodes->item(0);
// set attribute "hours"
$xmlShift->setAttribute("hours", $hours);
$xml->save($file);
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.