Modify existing XML file with DomDocument PHP - php

I have an existing xml file of the following format:
<root>
<word>
<label></label>
<definition></definition>
</word>
...
</root>
I'm taking in text through input boxes for the word and definition on the page and passing it to the php script via GET. The goal for the php script is to take the user input and add an additional word element containing the nested elements label (contains actual word) and definition (contains word definition) to the XML document vocab.xml.
Here is the script:
<?php
$word = $_GET['word'];
$definition = $_GET['definition'];
$dom = new DomDocument();
$dom->load("vocab.xml");
$root = $dom->documentElement;
$node = $dom->createElement("word");
$node2 = $dom->createElement("label", $word);
$node3 = $dom->createElement("definition", $definition);
$node->appendChild($node2);
$node->appendChild($node3);
$root->appendChild($node);
$dom->asXML("vocab.xml");
?>
As it stands now the script appears to execute correctly but checking the XML file reveals that no changes were made.

DOMDocument has no method asXML(). You need to use save():
$dom->save("vocab.xml");

Related

Adding or Updating XML Node PHP? [duplicate]

I just wanted to ask how I can insert a new node in an XML using PHP. my XML file (questions.xml) is given below
<?xml version="1.0" encoding="UTF-8"?>
<Quiz>
<topic text="Preparation for Exam">
<subtopic text="Science" />
<subtopic text="Maths" />
<subtopic text="english" />
</topic>
</Quiz>
I want to add a new "subtopic" with the "text" attribute, that is "geography". How can I do this using PHP? Thanks in advance though.
well my code is
<?php
$xmldoc = new DOMDocument();
$xmldoc->load('questions.xml');
$root = $xmldoc->firstChild;
$newElement = $xmldoc->createElement('subtopic');
$root->appendChild($newElement);
// $newText = $xmldoc->createTextNode('geology');
// $newElement->appendChild($newText);
$xmldoc->save('questions.xml');
?>
I'd use SimpleXML for this. It would look somehow like this:
// Open and parse the XML file
$xml = simplexml_load_file("questions.xml");
// Create a child in the first topic node
$child = $xml->topic[0]->addChild("subtopic");
// Add the text attribute
$child->addAttribute("text", "geography");
You can either display the new XML code with echo or store it in a file.
// Display the new XML code
echo $xml->asXML();
// Store new XML code in questions.xml
$xml->asXML("questions.xml");
The best and safe way is to load your XML document into a PHP DOMDocument object, and then go to your desired node, add a child, and finally save the new version of the XML into a file.
Take a look at the documentation : DOMDocument
Example of code:
// open and load a XML file
$dom = new DomDocument();
$dom->load('your_file.xml');
// Apply some modification
$specificNode = $dom->getElementsByTagName('node_to_catch');
$newSubTopic = $xmldoc->createElement('subtopic');
$newSubTopicText = $xmldoc->createTextNode('geography');
$newSubTopic->appendChild($newSubTopicText);
$specificNode->appendChild($newSubTopic);
// Save the new version of the file
$dom->save('your_file_v2.xml');
You can use PHP's Simple XML. You have to read the file content, add the node with Simple XML and write the content back.

What instead of createTextNode to not avoid XML paragraphs

I've got a php code which gets external xml file, adds something before last paragraph and saves it as new file.
<?php
$xmldoc = new DOMDocument();
$xmldoc->load('xml.xml');
$root = $xmldoc->firstChild;
$newElement = $xmldoc->createTextNode('<o id="1" url="link.html" price="899.00" avail="1" weight="0" stock="0" set="0" basket="0"></o>');
$root->appendChild($newElement);
$newText = $xmldoc->createTextNode($newAct);
$newElement->appendChild($newText);
$xmldoc->save('sample.xml');
?>
However, I don't want to lose XML signs like " <> ". What should I use instead of createTextNode? Because by now I've got a code like this:
<o id="1" url="link.html" price="899.00" avail="1" weight="0" stock="0" set="0" basket="0">
DOMDocument::createTextNode() does exactly that it creates a node containing text. It does not loose the special characters - they will be encoded as entities for the serialization.
Here are other methods like DOMDocument::createElement() to create an element node and DOMElement::setAttribute() to set attributes on an element node.
If you have an XML fragment as a string literal, here is a node type that can consume it. The DOMDocumentFragment.
$document = new DOMDocument();
$root = $document->appendChild($document->createElement('foo'));
$fragment = $document->createDocumentFragment();
$fragment->appendXml('<p>some text</p>');
$root->appendChild($fragment);
echo $document->saveXml();
Document fragments are kind of virtual nodes, the are a list of nodes with a single node as a container so that they can be passed to the DOM methods. Be careful using DOMDocumentFragment:appendXml() or you might open yourself to HTML/XML injections.
You are searching createElement.
<?php
$newElement = $xmldoc->createTextNode('o');
$newElement->setAttribute("url", "link.html");
You can then add attributes to match with your example.
See setAttribute. createTextNode creates only a text node, no XML. createElement, creates an XML element.

retrieve html and XML from a string with php

My project is to use CKEditor and create a plugin to create chart inside the page which will display the result
(in CKEditor just an img will appear when you use the plugin).
The plugin is already created,
when you use it, XML with the value and attribute needed is created inside CKEditor.
So the XML for the chart exist with writing text (format as <p> by CKEditor).
When you save inside the CKEditor, the XML and the text as HTML are sent to the database inside a string
(when I retrieve data from CKEditor it send a string).
Inside the database it is stored like this:
<?xml version="1.0"?>
<configuration>
<onglet pos="1" name="test">
<wysiwyg>
<code>
<p>test</p>
<p><graphique drawer="Line" interval="2" periode="semaine" titre="test" type="Relative">
<serie marqueur="Normal">
<index serial="---" type="di">3</index>
<typegroupe></typegroupe>
<intervalgroup></intervalgroup>
<periodgroup></periodgroup>
<groupverif>non</groupverif>
<unite>Kwh</unite>
<legend>test2</legend>
<color>#000000</color>
</serie>
</graphique></p>
</code>
</wysiwyg>
</onglet>
</configuration>
I get it inside a php page to displays my text and chart from CKEditor
Like this:
$test=200; //ID
$testxml=loadxml($test);
$testonglet=$testxml->onglet;
$testwysiwyg=$testonglet->wysiwyg;
$testcode=$testwysiwyg->code;
loadxml is a php function in another file:
$loadXml = THE QUERY TO RETRIEVE THE XML FROM THE DB
$reqload = mysql_fetch_array(mysql_query($loadXml));
$decode = html_entity_decode($reqload[0]);
$xml = simplexml_load_string($decode);
return $xml;
Now if I do var_dump($testcode);
I got:
object(SimpleXMLElement)#6 (1) { [0]=> string(403) "
test
4nonKwhtest2#000000
test après graph
" }
test and test après graph are just text but the 4nonKwhtest2#000000 are the XML value from the plugin chart.
I would like to parse the string to retrive the text and the XML (with his structure since I need it to create the chart with php).
I have already tested:
$testXML = Simplexml_load_string($testcode);
var_dump($testXML);
It gave me:
bool(false)
I have the same from XMLReader.
I also tested:
$dom = new DOMDocument();
$dom->loadHTML($testcode);
It gave something with the text but I couldn't retrieve my XML from it.
I don't know how to handle this anymore, it's the first time I use PHP
I hope it's more clear like this (sorry for my english).
Basically you have an XML document that contains another XML fragment as a text node.
That means you need to load the outer XML document first, read the text node and append the XML fragment to a new XML document.
Load The Outer XML / Read The Fragment:
DOMXpath::evaluate() allows to fetch nodes and values from a XML DOM using XPath expression.
$outer = new DOMDocument();
$outer->loadXml($xml);
$xpath = new DOMXPath($outer);
$innerXml = $xpath->evaluate('string(/configuration/onglet/wysiwyg/code)');
echo $innerXml;
Output:
<p>test</p>
<p><graphique drawer="Line" interval="2" periode="semaine" titre="test" type="Relative">
<serie marqueur="Normal">
<index serial="---" type="di">3</index>
<typegroupe></typegroupe>
<intervalgroup></intervalgroup>
<periodgroup></periodgroup>
<groupverif>non</groupverif>
<unite>Kwh</unite>
<legend>test2</legend>
<color>#000000</color>
</serie>
</graphique></p>
Load The XML Fragment
XML documents have a single root/document element node, so the XML in the case is a fragment. For easy reading it needs the single root node. So lets create a document with a body node and append the fragment to it:
$inner = new DOMDocument();
$inner->appendChild($inner->createElement('body'));
$fragment = $inner->createDocumentFragment();
$fragment->appendXml($innerXml);
$inner->documentElement->appendChild($fragment);
echo $inner->saveXml();
Output:
<?xml version="1.0"?>
<body>
<p>test</p>
<p><graphique drawer="Line" interval="2" periode="semaine" titre="test" type="Relative">
<serie marqueur="Normal">
<index serial="---" type="di">3</index>
<typegroupe></typegroupe>
<intervalgroup></intervalgroup>
<periodgroup></periodgroup>
<groupverif>non</groupverif>
<unite>Kwh</unite>
<legend>test2</legend>
<color>#000000</color>
</serie>
</graphique></p>
</body>
The element name doesn't matter, but body fits the p elements.
Read Data From The New Document
Now it is possible to create an DOMXPath instance for the document and fetch data from it.
$xpath = new DOMXPath($inner);
foreach ($xpath->evaluate('//graphique') as $graphique) {
var_dump(
[
'drawer' => $graphique->getAttribute('drawer'),
'serie-color' => $xpath->evaluate('string(serie/color)', $graphique)
]
);
}
Output:
array(2) {
["drawer"]=>
string(4) "Line"
["serie-color"]=>
string(7) "#000000"
}

Change the value of a text node using SimpleXML

I am trying to write a code where it will find a specific element in my XML file and then change the value of the text node. The XML file has different namespaces. Till now, I have managed to register the namespaces and also echo the text node of the element, which I want to change.
<?php
$xml = simplexml_load_file('getobs.xml');
$xml->registerXPathNamespace('g','http://www.opengis.net/gml');
$result = $xml->xpath('//g:beginPosition');
foreach ($result as $title) {
echo $title . "\n";
}
?>
My question is: How can I change the value of this element using SimpleXML? I tried to use the nodeValue command but I am not able to make it work.
This is a part of the XML:
<sos:GetObservation xmlns:sos="http://www.opengis.net/sos/1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" service="SOS" version="1.0.0" srsName="urn:ogc:def:crs:EPSG:4326">
<sos:offering>urn:gfz:cawa:def:offering:meteorology</sos:offering>
<sos:eventTime>
<ogc:TM_During xmlns:ogc="http://www.opengis.net/ogc" xsi:type="ogc:BinaryTemporalOpType">
<ogc:PropertyName>urn:ogc:data:time:iso8601</ogc:PropertyName>
<gml:TimePeriod xmlns:gml="http://www.opengis.net/gml">
<gml:beginPosition>2011-02-10T01:10:00.000</gml:beginPosition>
Thanks
Dimitris
In the end I managed to do it by using the PHP XML DOM.
Here is the code that I used in order to change the text node of a specific element:
<?php
// create new DOM document and load the data
$dom = new DOMDocument;
$dom->load('getobs.xml');
//var_dump($dom);
// Create new xpath and register the namespace
$xpath = new DOMXPath($dom);
$xpath->registerNamespace('g','http://www.opengis.net/gml');
// query the result amd change the value to the new date
$result = $xpath->query("//g:beginPosition");
$result->item(0)->nodeValue = 'sds';
// save the values in a new xml
file_put_contents('test.xml',$dom->saveXML());
?>
Not wanting to switch from the code I've already made for SimpleXML, I found this solution:
http://www.dotdragnet.com/forum/index.php?topic=3979.0
Specificially:
$numvotes = $xml->xpath('/gallery/image[path="'.$_GET["image"].'"]/numvotes');
...
$numvotes[0][0] = $votes;
Hope this helps!

How store xml file special characters values in its as it is?

I am using my xml file to store special chars.
This is my original file
<root>
<popups>
<popup id="1">
<text1>
<![CDATA[dynamic text popup 2a]]>
</text1>
<text2>
<![CDATA[dynamic text popup 2b]]>
</text2>
</popup>
</popups>
</root>
Now when I use php to save special chars eg , it becomes like that
<root>
<popups>
<popup id="1">
<text1><![CDATA[Hello world]]></text1>
<text2><![CDATA[asassa]]></text2>
</popup>
</popups>
</root>
I have used the following code :
$this->xmlDocument = simplexml_load_file("xml/conf.xml");
$pages_node = $this->xmlDocument->xpath("/root/popups/popup[#id=1]");
$name = $_POST['popup-name'];
$editor1 = trim(strip_tags($_POST['editor1']));
$editor2 = trim(strip_tags($_POST['editor2']));
if (!empty($name)){
if (!empty($editor1)){
$pages_node[0]->text1 = "<![CDATA[".$editor1."]]>";
}
if (!empty($editor2)){
$pages_node[0]->text2 = "<![CDATA[".$editor2."]]>" ;
}
$this->xmlDocument->asXml($this->basePath() . "conf/conf.xml");
}
How can I save the special chars as they are without needing to encode them?
Simplexml is meant to be simple, so there is no such option. dom_import_simplexml can help you create domdocument from simplexml object.
You have to create new instance of DOMDocument, then create CDATA section and put it into imported DOMElement node.
If you are using php DomDocument, you have to create DOMCDATASection and append it to text1/text2 nodes.
If you don't have text1 and text2 nodes, you have to create them first, then appencd cdata node to them and finally append them to popup:
$cdata = $dom->createCDATASection("test");
$text1 = $dom->createElement('text1');
$text1->appendChild($cdata);
$text1 = $dom->createElement('text2');
$text2->appendChild($cdata);
$popupNode->appendChild($text1);
$popupNode->appendChild($text2);

Categories