I want to add an XML tree into another XML, and I have tried with following code which is not working:
<?php
$str1 = '<parent>
<name>mrs smith</name>
</parent>';
$xml1 = simplexml_load_string($str1);
print_r($xml1);
$str2 = '<tag>
<child>child1</child>
<age>3</age>
</tag>';
$xml2 = simplexml_load_string($str2);
print_r($xml2);
$xml1->addChild($xml2);
print_r($xml1);
?>
Expect output XML:
<parent>
<name>mrs smith</name>
<tag>
<child>child1</child>
<age>3</age>
</tag>
</parent>
Please assist me.
You can use DOMDocument::importNode
<?php
$str2 = '<tag>
<child>child1</child>
<age>3</age>
</tag>';
$str1 = '<parent>
<name>mrs smith</name>
</parent>';
$tagDoc = new DOMDocument;
$tagDoc->loadXML($str2);
$tagNode = $tagDoc->getElementsByTagName("tag")->item(0);
//echo $tagDoc->saveXML();
$newdoc = new DOMDocument;
$newdoc->loadXML($str1);
$node = $newdoc->importNode($tagNode, true);
$newdoc->documentElement->appendChild($node);
echo $newdoc->saveXML();die;
Related
Is there a why to do this? I'm new on create DomDocument. Thank you
<!DOCTYPE Data SYSTEM "http://data.data.org/schemas/data/1.234.1/data.dtd"> <Data payloadID = "123123123131231232323" timestamp = "2015-06-10T12:59:09-07:00">
$aribaXML = new DOMImplementation;
$dtd = $aribaXML->createDocumentType('cXML', '', 'http://xml.cxml.org/schemas/cXML/1.2.014/cXML.dtd');
$dom = $aribaXML->createDocument('', '', $dtd);
Here are two ways in DOM to create a new document in PHP. If you don't need the DTD you can directly create an instance of the DOMDocument class.
$document = new DOMDocument('1.0', "UTF-8");
$document->appendChild(
$cXML = $document->createElement('cXML')
);
echo $document->saveXML();
Output:
<?xml version="1.0" encoding="UTF-8"?>
<cXML/>
For a document with a DTD your approach was correct.
$implementation = new DOMImplementation;
$dtd = $implementation->createDocumentType(
'cXML', '', 'http://xml.cxml.org/schemas/cXML/1.2.014/cXML.dtd'
);
$document = $implementation->createDocument("", "cXML", $dtd);
$document->encoding = 'UTF-8';
$cXML = $document->documentElement;
echo $document->saveXML();
Output:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE cXML SYSTEM "http://xml.cxml.org/schemas/cXML/1.2.014/cXML.dtd">
After the initial bootstrap you use methods of the $document to create nodes and append them.
// set an attribute on the document element
$cXML->setAttribute('version', '1.1.007');
// xml:lang is a namespaced attribute in a reserved namespace
$cXML->setAttributeNS('http://www.w3.org/XML/1998/namespace', 'xml:lang', 'en-US');
// nested elements
// create a node, store it for the next call and append it
$cXML->appendChild(
$header = $document->createElement('Header')
);
$header->appendChild(
$from = $document->createElement('From')
);
$from->appendChild(
$credential = $document->createElement('Credential')
);
// "Identity" has only a text node so we don't need to store it for later
$credential->appendChild(
$document->createElement('Identity')
)->textContent = '83528721';
// format serialized XML string
$document->formatOutput = TRUE;
echo $document->saveXML();
Output:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE cXML SYSTEM "http://xml.cxml.org/schemas/cXML/1.2.014/cXML.dtd">
<cXML version="1.1.007" xml:lang="en-US">
<Header>
<From>
<Credential>
<Identity>83528721</Identity>
</Credential>
</From>
</Header>
</cXML>
$xml = new DomDocument('1.0');
$xml->formatOutput = true;
$works = $xml->createElement("works");
$xml->appendChild($works);
$work = $xml->createElement("work");
$work->setAttribute("id",1);
$works->appendChild($work);
$xml->save("storage/document.xml") or die("Error, Unable to create XML File");
I want to save space by saving the xml file in minified form
for example
<body>
<div>
<p>hello</p>
<div/>
</div>
</body>
it should be saved like this
<body><div><p>hello</p><div/></div></body>
I'm using DOMDocument to create xml file like this
$xml = new DOMDocument("1.0", "UTF-8");
$xml->preserveWhiteSpace = false;
$xml->formatOutput = false;
$feed = $xml->createElement("feed");
$feed = $xml->appendChild($feed);
/*add attribute*/
$feed_attribute = $xml->createAttribute('xmlns:xsi');
$feed_attribute->value = 'http://www.w3.org/2001/XMLSchema-instance';
$feed->appendChild($feed_attribute);
$aggregator = $xml->createElement("aggregator");
$aggregator = $feed->appendChild($aggregator);
$name = $xml->createElement('name', 'test.com');
$aggregator->appendChild($name);
...etc
$xml->save(public_path() .$string, LIBXML_NOEMPTYTAG);
You're already using the right options. DOMDocument::$formatOutput and DOMDocument::$preserveWhiteSpace:
Format Output
DOMDocument::$formatOutput adds indentation whitespace nodes to an XML DOM if saved. (It is disabled by default.)
$document = new DOMDocument();
$body = $document->appendChild($document->createElement('body'));
$div = $body->appendChild($document->createElement('div'));
$div
->appendChild($document->createElement('p'))
->appendChild($document->createTextNode('hello'));
echo "Not Formatted:\n", $document->saveXML();
$document->formatOutput = TRUE;
echo "\nFormatted:\n", $document->saveXML();
Output:
Not Formatted:
<?xml version="1.0"?>
<body><div><p>hello</p></div></body>
Formatted:
<?xml version="1.0"?>
<body>
<div>
<p>hello</p>
</div>
</body>
However it does not indent if here are text child nodes. It tries to avoid changes to the text output of an HTML/XML document. So it will usually not reformat a loaded document with existing indention whitespace nodes.
Preserve White Space
DOMDocument::$preserveWhiteSpace is an option for the parser. If disabled (It is enabled by default) the parser will ignore any text nodes that would consists of only whitespaces. Indentations are text nodes with a linebreak and some spaces or tabs. It can be used to remove indentations from an XML.
$xml = <<<'XML'
<?xml version="1.0"?>
<body>
<div>
<p>hello</p>
</div>
</body>
XML;
$document = new DOMDocument();
$document->preserveWhiteSpace = FALSE;
$document->loadXML($xml);
echo $document->saveXML();
Output:
<?xml version="1.0"?>
<body><div><p>hello</p></div></body>
Try this, you have to use saveXML() instead of save(),
<?php
$xml = new DOMDocument('1.0');
$xml->preserveWhiteSpace = false;
$xml->formatOutput = false;
$root = $xml->createElement('book');
$root = $xml->appendChild($root);
$title = $xml->createElement('title');
$title = $root->appendChild($title);
$text = $xml->createTextNode("This is the \n title");
$text = $title->appendChild($text);
echo "Saving all the document:\n";
$xml_content = $xml->saveXML();
echo $xml_content . "\n";
$xml_content = str_replace(array(">\n", ">\t"), '>', trim($xml_content, "\n"));
echo $xml_content . "\n";
// Write the contents back to the file
$filename = "/tmp/xml_minified.xml";
file_put_contents($filename, $xml_content);
?>
I have a question: I am trying to create a XML file using DomDocument and I would like to have this output:
<?xml version="1.0" encoding="UTF-8"?>
<winstrom version="1.0">
<main_tag>
<child_tag>example</child_tag>
</main_tag>
<winstrom>
The problem is with the second row - if I write it as below then the output is "Invalid Character Error". I guess it is not allowed to have space characters there... However I need it like this, so what are the options?
$dom = new DomDocument('1.0', 'UTF-8');
$root = $dom->createElement('winstrom version=1.0');
$dom->appendChild($root);
$item = $dom->createElement('hlavni_tag');
$root2->appendChild($item);
$text = $dom->createTextNode('example');
$item->appendChild($text);
$dom->formatOutput = true;
echo $dom->saveXML();
There seems to be a misunderstanding of what an XML element is and how it differs from attributes.
Try this code:
<?php
$dom = new DomDocument('1.0', 'UTF-8');
$root = $dom->createElement('winstrom');
$root->setAttribute("version","1.0");
$dom->appendChild($root);
$root2 = $dom->createElement("main_tag"); //You forgot this part
$root->appendChild($root2);
$item = $dom->createElement('hlavni_tag'); //Should it be "child_tag"?
$root2->appendChild($item);
$text = $dom->createTextNode('example');
$item->appendChild($text);
$dom->formatOutput = true;
echo $dom->saveXML();
i am using following code to create xml file using php
$doc = new DOMDocument('1.0');
$doc->formatOutput = true;
$root = $doc->createElement('alerts');
$root = $doc->appendChild($root);
$alert = $doc->createElement('alert');
$alert = $root->appendChild($alert);
$id = $doc->createElement('id');
$id_text = $doc->createTextNode($api_id);
$id->appendChild($id_text);
$alert->appendChild($id);
$msg_type = $doc->createElement('msg_type');
$msg_type_text = $doc->createTextNode(1);
$msg_type->appendChild($msg_type_text);
$alert->appendChild($msg_type);
$doc->save($filename);
it saves xml file well formatted like this
<?xml version="1.0"?>
<alerts>
<alert>
<id>22</id>
<msg_type>1</msg_type>
</alert>
</alerts>
but when i append tags in existing file with following code it will not formatted
$doc = new DOMDocument();
$doc->formatOutput = true;
$xml = file_get_contents($filename);
$doc->loadXML($xml);
$root = $doc->firstChild;
$alert = $doc->createElement('alert');
$alert = $root->appendChild($alert);
$id = $doc->createElement('id');
$id_text = $doc->createTextNode($api_id);
$id->appendChild($id_text);
$alert->appendChild($id);
$msg_type = $doc->createElement('msg_type');
$msg_type_text = $doc->createTextNode(1);
$msg_type->appendChild($msg_type_text);
$alert->appendChild($msg_type);
$doc->save($filename);
xml file format will be like this
<alerts>
<alert>
<id>3</id>
<msg_type>1</msg_type>
<msg>Api Name:Loop LM (H-PO) has low credit.</msg>
<url>common/api/view_sms_api_list.php</url>
<status>0</status>
<create_date>1387351877</create_date>
</alert>
<alert><id>6</id><msg_type>1</msg_type></alert><alert><id>14</id><msg_type>1</msg_type></alert><alert><id>24</id><msg_type>1</msg_type></alert></alerts>
it will continue in single line when i append a alert tag in this xml file. what is the problem?
thanks in advance.
Add $doc->preserveWhiteSpace = false; before load your doc $doc->loadXML($xml);
here i am creating xml file dynamically at run time but i m getting error
XML Parsing Error: junk after document element
Location: http://localhost/tam/imagedata.php?imageid=8
Line Number 9, Column 1:
^
$id=$_GET['imageid'];
$dom = new DomDocument('1.0');
$query="select * from tbl_image_gallery where imageId='$id'";
$select=mysql_query($query);
while($res=mysql_fetch_array($select))
{
$content = $dom->appendChild($dom->createElement('content'));
$image = $content->appendChild($dom->createElement('image'));
$small_image_path = $image->appendChild($dom->createElement('small_image_path'));
$small_image_path->appendChild($dom->createTextNode("load/images/small/".$res['image']));
$big_image_path = $image->appendChild($dom->createElement('big_image_path'));
$big_image_path->appendChild($dom->createTextNode("load/images/big/".$res['image']));
$description = $image->appendChild($dom->createElement('description'));
$description->appendChild($dom->createTextNode($res['description']));
$dom->formatOutput = true;
}
echo $test1 = $dom->saveXML();
and xml format is
<?xml version="1.0"?>
<content>
<image>
<small_image_path>load/images/small/1.jpg</small_image_path>
<big_image_path>load/images/big/1.jpg</big_image_path>
<description>hgjghj</description>
</image>
<image><small_image_path>load/images/small/2.jpg</small_image_path><big_image_path>load/images/big/2.jpg</big_image_path><description>fgsdfg</description></image><image><small_image_path>load/images/small/3.jpg</small_image_path><big_image_path>load/images/big/3.jpg</big_image_path><description>sdfgsdfg</description></image><image><small_image_path>load/images/small/4.jpg</small_image_path><big_image_path>load/images/big/4.jpg</big_image_path><description>gsbhsg</description></image><image><small_image_path>load/images/small/4.jpg</small_image_path><big_image_path>load/images/big/4.jpg</big_image_path><description>gsbhsg</description></image><image><small_image_path>load/images/small/avatar.jpg</small_image_path><big_image_path>load/images/big/avatar.jpg</big_image_path><description></description></image></content>
Can it be that you are posting html code into the description field?
Could be usefull to add a CDataSection instead of a TextNode
$cdata = $dom->createCDATASection($res['description']);
$image->appendChild($cdata);