please help.
I have XML file which is not filled correctly (some values are missed)
Bad example of XML
<?xml version="1.0"?>
<csv_data>
<row>
<brand>Maxxis</brand>
<code>1126668/02</code>
<articul_brand></articul_brand>
<tiporazmer></tiporazmer>
<name>(26/9.00 R12) 6PR TL</name>
<model>M-966 Mudzilla</model>
<sklad_msk></sklad_msk>
<sklad_nahabino></sklad_nahabino>
<sklad_chelny>8</sklad_chelny>
<price_big_opt>6,786р.</price_big_opt>
<price_small_opt>7,100р.</price_small_opt>
<price_retail>8,170р.</price_retail>
</row>
</csv_data>
Good example of XML
<?xml version="1.0"?>
<csv_data>
<row>
<brand>Metzeler</brand>
<code>ЦО04257/21</code>
<articul_brand>2491500</articul_brand>
<tiporazmer>110/80R18</tiporazmer>
<name>(110/80 R18) 58W TL (M) Front</name>
<model>Roadtec Z8</model>
<sklad_msk></sklad_msk>
<sklad_nahabino>2</sklad_nahabino>
<sklad_chelny></sklad_chelny>
<price_big_opt>7,720р.</price_big_opt>
<price_small_opt>8,106р.</price_small_opt>
<price_retail>9,270р.</price_retail>
</row>
</csv_data>
The point is that values in <tiporazmer></tiporazmer> are missed in bad example but they can be found in <name>(26/9.00 R12) 6PR TL</name>
The question is how to update fields <tiporazmer></tiporazmer> using name filed? Copy that without brackets? How?
What I did, but i've got an error Fatal error: Call to a member function getElementsByTagName() on a non-object in
Code:
<?php
$xml = new DOMDocument('1.0', 'utf-8');
$xml->formatOutput = true;
$xml->preserveWhiteSpace = false;
$xml->load('test2.xml');
$new_tiporazmer="26/9.00 R12";
//Get item Element
$element = $xml->getElementsByTagName('rows')->item(0);
//Load child elements
$tiporazmer = $element->getElementsByTagName('tiporazmer')->item(0);
//Replace old elements with new
$element->replaceChild($tiporazmer, $new_tiporazmer);
?>
The error is caused because you're calling getElementsByTagName('rows'), but the name of your XML node is row, so there shouldn't be an s in rows
Then in order to Replace old elements with new, you will need to use nodeValue instead of replaceChild unless you already have a constructed DOMDocument object ready.
But a better way to achieve what you want is to simply find the element by name directly, replace its text, and then save as a new file. I saved to the "/tmp" folder because permissions are usually writeable there on unix systems, but you can write anywhere your php interpreter is allowed.
<?php
$xml = new DOMDocument('1.0', 'utf-8');
$xml->formatOutput = true;
$xml->preserveWhiteSpace = false;
$xml->load('test2.xml');
$new_tiporazmer="26/9.00 R12";
//Get item Element and Replace old elements with new
$xml->getElementsByTagName('tiporazmer')->item(0)->nodeValue = $new_tiporazmer;
//Save as new file
$xml->save("/tmp/good.xml");
This results in good.xml:
<?xml version="1.0"?>
<csv_data>
<row>
<brand>Maxxis</brand>
<code>1126668/02</code>
<articul_brand/>
<tiporazmer>26/9.00 R12</tiporazmer>
<name>(26/9.00 R12) 6PR TL</name>
<model>M-966 Mudzilla</model>
<sklad_msk/>
<sklad_nahabino/>
<sklad_chelny>8</sklad_chelny>
<price_big_opt>6,786р.</price_big_opt>
<price_small_opt>7,100р.</price_small_opt>
<price_retail>8,170р.</price_retail>
</row>
</csv_data>
Related
Let's say I have the following .xml file:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<item>
<name>Foo</name>
</item>
<item>
<name>Bar</name>
</item>
</root>
In this sample file, I'm trying to append new nodes <item> to node <root> after the last node <item>.
I'm trying to append newly created <item> nodes after the last <item> node in the <root> node in the .xml file.
<?php
$file = new DOMDocument;
$file->load("xml.xml");
$file->loadXML($file->saveXML());
$root = $file->getElementsByTagName('root')->item(0);
foreach (["Foo_1", "Bar_2", "Foo_3", "Bar_4"] as $val) {
$item = new DOMElement('item');
$item->appendChild(new DOMElement('name', $val));
$root->appendChild(item);
}
?>
But I'm getting an error:
Fatal error: Uncaught Error: Call to a member function appendChild() on null in C:\Users\pfort\Desktop\p.php:12
Stack trace:
#0 {main}
thrown in C:\Users\user_acer\Desktop\p.php on line 12
What am I doing wrong?
There's multiple issues with your example code. I will address the error you received first:
There is no element <terminy> in your example XML, so
$root = $file->getElementsByTagName('terminy')->item(0);
will return null. That's why you are receiving the
Call to a member function appendChild() on null
error at
$root->appendChild(item);
Also, item is a typo, because it's not a valid variable name (but a name for a non-existent constant); you meant $item.
I'm assuming "terminy" means something similar to "root" in your native language and that you actually meant to write
$root = $file->getElementsByTagName('root')->item(0);
By the way: if you want a reference to the root node of an XML document, you can also use $file->docomentElement.
However, there are other issues with your example code:
$file->load("xml.xml");
$file->loadXML($file->saveXML()); // why are you reloading it in this way?
The last line is unnecessary. You are reloading the same XML again. Is it for formatting purposes? If so, there's a better option available:
$file->preserveWhiteSpace = false;
$file->formatOutput = true;
$file->load("xml.xml");
Lastly: you cannot append children to a node that has not been associated with a document yet. So, to create a new item and associate it with the document, you either do (recommended):
// automatically associate new nodes with document
$item = $file->createElement('item');
$item->appendChild($file->createElement('name', $val));
or (more cumbersome):
// import nodes to associate them with document
$item = $file->importNode(new DOMElement('item'));
$item->appendChild($file->importNode(new DOMElement('name', $val)));
So, putting it all together it becomes:
<?php
$xml = <<<'XML'
<?xml version="1.0" encoding="UTF-8"?>
<root>
<item>
<name>Foo</name>
</item>
<item>
<name>Bar</name>
</item>
</root>
XML;
$file = new DOMDocument;
$file->preserveWhiteSpace = false;
$file->formatOutput = true;
$file->loadXML($xml); // (for demo purpose loading above XML) replace this with $file->load("xml.xml"); in your actual code
$root = $file->documentElement;
foreach (["Foo_1", "Bar_2", "Foo_3", "Bar_4"] as $val) {
$item = $file->createElement('item');
$item->appendChild($file->createElement('name', $val));
$root->appendChild($item);
}
echo $file->saveXML();
**PROBLEM SOLVED**
I lost too much time on this problem. The good news is, I already know how to get what I need. Here I offer a solution - for everyone who will need to solve the same problem.
Perhaps this solution will be useful for anyone who needs it.
<?php
// snippet of xml temple
$xml = <<<XML
<item date="%s" status="%s">
<name>%s</name>
</item>
XML;
// prepare snippet
$xmlSnippet = sprintf($xml, "2022-11-21", 0, "Foo Bar");
// new DOMDocument
$dom = new DOMDocument;
$dom->preserveWhiteSpace = 0;
$dom->formatOutput = 1;
// load of .xml file content and load to DOMDocument object
$file = simplexml_load_file("xml.xml");
$dom->loadXML($file->asXML());
// creating of fragment from snippet
$fragment = $dom->createDocumentFragment();
$fragment->appendXML($xmlSnippet);
//append the snippet to the DOMDocument
// and save it to the xml.xml file
$dom->documentElement->appendChild($fragment);
$dom->save("xml.xml");
?>
Result:
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.
While adding child, this error is thrown :
Cannot add child. Parent is not a permanent member of the XML tree.
I cannot resolve this.
This is my code :
if($visited=='FIRST')
{
$xml=new SimpleXMLElement("<xml/>");
$topology=$xml->addChild("Topology_Configuration");
$flavor=$topology->addChild("Flavor");
$networks=$topology->addChild("Networks");
$vms=$topology->addChild("VMs");
$vnfs=$topology->addChild("VNFs");
$xml->asXML('saddening.xml');
}
else
{
$xml= simplexml_load_file('saddening.xml');
$Topology_Configuration = new SimpleXMLElement($xml->asXML());
$vmcount=$_POST['arguments']['vmcount'];
$flavor=$Topology_Configuration->Flavor;
$flavor_name=$flavor->addChild($_POST['arguments']['flavorName']);
$Topology_Configuration->asXML('saddening.xml');
}
When it is executed for the first time, the file is created(in if part). Otherwise else part is executed. It cannot add the child and is throwing the error in line :
$flavor_name=$flavor->addChild($_POST['arguments']['flavorName']);. Please help!!
The XML from your first run results in an XML like this:
<?xml version="1.0"?>
<xml>
<Topology_Configuration>
<Flavor/>
<Networks/>
<VMs/><VNFs/>
</Topology_Configuration>
</xml>
So if you strip down the problem you can reproduce it with:
$Topology_Configuration = simplexml_load_file($fileName);
$flavor=$Topology_Configuration->Flavor;
$flavor->addChild('abc');
echo $Topology_Configuration->asXml();
Results in:
Warning: SimpleXMLElement::addChild(): Cannot add child.
Parent is not a permanent member of the XML tree in
The message is a little wrong, you just try to add the element to an element that does not exists. $Topology_Configuration contains the xml element node, not the Topology_Configuration.
Here are two possible solutions:
Change the XML structure
Create the XML with the Topology_Configuration as the root element.
$topology =new SimpleXMLElement("<Topology_Configuration/>");
Change the access to the Flavor
$xml = simplexml_load_file($fileName);
$flavor=$xml->Topology_Configuration->Flavor;
$flavor->addChild('abc');
At the first time, you can use example to add child nodes
$new_xml = new SimpleXMLElement("<root></root>");
$new_xml->addAttribute('newAttr', 'value');
$newsIntro = $new_xml->addChild('content');
$newsIntro->addAttribute('type', 'value');
Header('Content-type: text/xml');
echo $new_xml->asXML();
and result
<?xml version="1.0"?>
<news newAttr="value">
<content type="value"/>
</news
If I have the following structure in an XML File;
<?xml version="1.0" encoding="UTF-8"?>
<Document xmlns="urn:iso:std:iso:20022:tech:xsd:pain.008.001.02" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<CstmrDrctDbtInitn>
<GrpHdr>
<MsgID>rBYEqfjzEU</MsgID>
<CreDtTm>2014-07-01T12:36:15</CreDtTm>
<NbOfTxs>2</NbOfTxs>
<CtrlSum>400.4</CtrlSum>
<InitgPty>
<Id>
<PrvtId>
<Othr>
<Id>IA1234567</Id>
</Othr>
</PrvtId>
</Id>
</InitgPty>
</GrpHdr>
</CstmrDrctDbtInitn>
</Document>
The above code represents one transaction between the <CstmrDrctDbtInitn> and <\CstmrDrctDbtInitn> tags. This file will be appended to include more transactions which will all start and end with a <CstmrDrctDbtInitn> and <\CstmrDrctDbtInitn> tags. I need to count the number of transactions in the file, so i basically need to count the number of <CstmrDrctDbtInitn> tags in the file. Any suggestions? Sorry if I am explaining this badly, confused!
I altered the following PHP code as suggested but no luck :(
$filename = date('Y-W').'.xml'; //2014-26.xml
//Check if a file exists
if (file_exists($filename))
{
$dom = simplexml_load_string($xml);
global $NumberTransactions;
$NumberTransactions = count($dom->CstmrDrctDbtInitn);
// call xml appendFile function
appendFile($filename);
}
else
{
// call xml createFile function
createFile($filename);
}
Assuming you mean to count the number of child nodes under GrpHdr - you could use SimpleXML:
$xml = '<?xml version="1.0" encoding="UTF-8"?>
<Document xmlns="urn:iso:std:iso:20022:tech:xsd:pain.008.001.02" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<CstmrDrctDbtInitn>
<GrpHdr>
<MsgID>rBYEqfjzEU</MsgID>
<CreDtTm>2014-07-01T12:36:15</CreDtTm>
<NbOfTxs>2</NbOfTxs>
<CtrlSum>400.4</CtrlSum>
<InitgPty>
<Id>
<PrvtId>
<Othr>
<Id>IA1234567</Id>
</Othr>
</PrvtId>
</Id>
</InitgPty>
</GrpHdr>
</CstmrDrctDbtInitn>
</Document>';
$dom = simplexml_load_string($xml);
// var_dump($dom->CstmrDrctDbtInitn->GrpHdr);
echo count($dom->CstmrDrctDbtInitn->GrpHdr->children());
If you meant a variation you should be able to get a good clue of the structure by uncommenting that var_dump line and working through the object structure.
If you meant something else - give us a clue by telling us in detail what you wanted the count value to be based on your example data.
===================== UPDATED FOLLOWING CLARIFICATION BELOW=============
To count the number of CstmrDrctDbtInitn groups you can use the original example, but instead the count line would be:
echo count($dom->CstmrDrctDbtInitn);
DOMXpath::evaluate() can use Xpath to count the nodes.
// create and load
$dom= new DOMDocument();
$dom->loadXml($xml);
$xpath = new DOMXpath($dom);
// register an alias/prefix for the namespace
$xpath->registerNamespace('iso', 'urn:iso:std:iso:20022:tech:xsd:pain.008.001.02');
// get the count
var_dump($xpath->evaluate('count(//iso:CstmrDrctDbtInitn)'));
Demo: https://eval.in/169122
I was tesing with a simple example of how to display XML in browser using PHP and found this example which works good
<?php
$xml = new DOMDocument("1.0");
$root = $xml->createElement("data");
$xml->appendChild($root);
$id = $xml->createElement("id");
$idText = $xml->createTextNode('1');
$id->appendChild($idText);
$title = $xml->createElement("title");
$titleText = $xml->createTextNode('Valid');
$title->appendChild($titleText);
$book = $xml->createElement("book");
$book->appendChild($id);
$book->appendChild($title);
$root->appendChild($book);
$xml->formatOutput = true;
echo "<xmp>". $xml->saveXML() ."</xmp>";
$xml->save("mybooks.xml") or die("Error");
?>
It produces the following output:
<?xml version="1.0"?>
<data>
<book>
<id>1</id>
<title>Valid</title>
</book>
</data>
Now I have got two questions regarding how the output should look like.
The first line in the xml file '', should not be displayed, that is it should be hidden
How can I display the TextNode in the next line. In total I am exepecting an output in this fashion
<data>
<book>
<id>1</id>
<title>
Valid
</title>
</book>
</data>
Is that possible to get the desired output, if so how can I accomplish that.
Thanks
To skip the XML declaration you can use the result of saveXML on the root node:
$xml_content = $xml->saveXML($root);
file_put_contents("mybooks.xml", $xml_content) or die("cannot save XML");
Please note that saveXML(node) has a different output from saveXML().
First question:
here is my post where all usable threads with answers are listed: How do you exclude the XML prolog from output?
Second question:
I don't know of any PHP function that outputs text nodes like that.
You could:
read xml using DomDocument and save each node as string
iterate trough nodes
detect text nodes and add new lines to xml string manually
At the end you would have the same XML with text node values in new line:
<node>
some text data
</node>