XML PHP Format Setup - php

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");

Related

generating sitemap with DOMDocument : missing AttributeNode in the output

im trying to generate a sitemap.xml , here is simplified version of my code
$dom = new \DOMDocument();
$dom->encoding = 'utf-8';
$dom->xmlVersion = '1.0';
$dom->formatOutput = true;
$xml_file_name = './sitemap.xml';
$urlset = $dom->createElement('urlset');
$attr_ = new \DOMAttr('xmlns:xsi', "http://www.w3.org/2001/XMLSchema-instance");
$urlset->setAttributeNode($attr_);
$url_node = $dom->createElement('url');
$url_node_loc = $dom->createElement('loc', 'http://localhost' );
$url_node->appendChild($url_node_loc);
$url_node_lastmod = $dom->createElement('lastmod', '2021-08-03T22:17:47+04:30' );
$url_node->appendChild($url_node_lastmod);
$urlset->appendChild($url_node);
$dom->appendChild($urlset);
$dom->save($xml_file_name);
dd('done');
here is the output in my sitemap.xml
This XML file does not appear to have any style information associated with it. The document tree is shown below.
<urlset>
<url>
<loc>http://localhost</loc>
<lastmod>2021-08-03T22:17:47+04:30</lastmod>
</url>
</urlset>
i need to add some attributes to my urlset tag , here is how i've did it
$attr_ = new \DOMAttr('xmlns:xsi', "http://www.w3.org/2001/XMLSchema-instance");
$urlset->setAttributeNode($attr_);
but for some reason this doesn't show up in my sitemap file , urlset has no attributes
Use setAttribute() instead of setAttributeNode().
$urlset->setAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
This will not be a valid sitemap. Sitemaps use an XML namespace (https://www.sitemaps.org/protocol.html)
To create nodes with namespaces you should use the namespace aware DOM methods with the *NS suffix. This will add namespace definitions as needed.
xmlns:xsi is a namespace definition. They can be considered attributes nodes in the reserved namespace {http://www.w3.org/2000/xmlns/}.
$xmlns = [
'sitemap' => 'http://www.sitemaps.org/schemas/sitemap/0.9',
'xmlns' => 'http://www.w3.org/2000/xmlns/',
'xsi' => 'http://www.w3.org/2001/XMLSchema-instance',
];
$document = new \DOMDocument('1.0', 'utf-8');
$document->formatOutput = true;
$urlset = $document->appendChild(
$document->createElementNS($xmlns['sitemap'], 'urlset')
);
// explict namespace definition
$urlset->setAttributeNS(
$xmlns['xmlns'], 'xmlns:xsi', $xmlns['xsi']
);
$url_node = $urlset->appendChild(
$document->createElementNS($xmlns['sitemap'], 'url')
);
$url_node
->appendChild($document->createElementNS($xmlns['sitemap'], 'loc'))
->textContent = 'http://localhost';
$url_node
->appendChild($document->createElementNS($xmlns['sitemap'], 'lastmod'))
->textContent = '2021-08-03T22:17:47+04:30';
echo $document->saveXML();
Output:
<?xml version="1.0" encoding="utf-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<url>
<loc>http://localhost</loc>
<lastmod>2021-08-03T22:17:47+04:30</lastmod>
</url>
</urlset>

simpleXMLElement remove by yourself encoding

I need to create an XML in PHP.
My code start with:
$doc = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><iv:Fornitura xmlns:cm="urn:www.agenziaentrate.gov.it:specificheTecniche:common" xmlns:ds="http://www.w3.org/2000/09/xmldsig#" xmlns:tm="urn:www.agenziaentrate.gov.it:specificheTecniche:telent:v1" xmlns:iv="urn:www.agenziaentrate.gov.it:specificheTecniche:sco:ivp"></iv:Fornitura>', LIBXML_NOERROR, false, 'iv', true);
$dom = new DOMDocument('1.0');
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom_xml = dom_import_simplexml($doc);
$dom_xml = $dom->importNode($dom_xml, true);
$dom_xml = $dom->appendChild($dom_xml);
$file_XML = $dom->saveXML(); // SAVE TO STRING
Expected result:
<?xml version="1.0" encoding="UTF-8"?>
<iv:Fornitura xmlns:cm="urn:www.agenziaentrate.gov.it:specificheTecniche:common" xmlns:ds="http://www.w3.org/2000/09/xmldsig#" xmlns:iv="urn:www.agenziaentrate.gov.it:specificheTecniche:sco:ivp">
</iv:Fornitura>
But I always get:
<?xml version="1.0"?>
<iv:Fornitura xmlns:cm="urn:www.agenziaentrate.gov.it:specificheTecniche:common" xmlns:ds="http://www.w3.org/2000/09/xmldsig#" xmlns:iv="urn:www.agenziaentrate.gov.it:specificheTecniche:sco:ivp">
</iv:Fornitura>
It seem encoding encoding="UTF-8" disappear. Using also addAttribute doesn't work.
Rather than disappearing, I'd say it never gets added in the first place:
$dom = new DOMDocument('1.0');
As per docs:
public DOMDocument::__construct ([ string $version [, string $encoding ]] )`
Demo

Duplicate xml namespace declarations php DOMDocument

I use PHP DOMDocument to generate xml. Sometimes namespaces are declared only on root element, which is intended behaviour, but sometimes no.
For example:
$xml = new DOMDocument('1.0', 'utf-8');
$ns = "http://ns.com";
$otherNs = "http://otherns.com";
$docs = $xml->createElementNS($ns, "ns:Documents");
$doc = $xml->createElementNS($otherNs, "ons:Document");
$innerElement = $xml->createElementNS($otherNs, "ons:innerElement", "someValue");
$doc->appendChild($innerElement);
$docs->appendChild($doc);
$xml->appendChild($docs);
$xml->formatOutput = true;
$xml->save("dom");
I expect:
<?xml version="1.0" encoding="UTF-8"?>
<ns:Documents xmlns:ns="http://ns.com" xmlns:ons="http://otherns.com">
<ons:Document>
<ons:innerElement>someValue</ons:innerElement>
</ons:Document>
</ns:Documents>
But got:
<?xml version="1.0" encoding="UTF-8"?>
<ns:Documents xmlns:ns="http://ns.com" xmlns:ons="http://otherns.com">
<ons:Document xmlns:ons="http://otherns.com">
<ons:innerElement>someValue</ons:innerElement>
</ons:Document>
</ns:Documents>
Why declaration of xmlns:ons="http://otherns.com" appears on Document element, but not in <innerElement>? And how to prevent duplicates?
It's very easy. Just add your nodes into document tree.
Additionally you can explicitly create xmlns:XXX atrtribute in root node.
See example:
namespace test;
use DOMDocument;
$xml = new DOMDocument("1.0", "UTF-8");
$ns = "http://ns.com";
$otherNs = "http://otherns.com";
$docs = $xml->createElementNS($ns, "ns:Documents");
$xml->appendChild($docs);
$docs->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:ons', $otherNs);
$doc = $xml->createElement("ons:Document");
$docs->appendChild($doc);
$innerElement = $xml->createElement("ons:innerElement", "someValue");
$doc->appendChild($innerElement);
$xml->formatOutput = true;
echo $xml->saveXML();
Result:
<?xml version="1.0" encoding="UTF-8"?>
<ns:Documents xmlns:ns="http://ns.com" xmlns:ons="http://otherns.com">
<ons:Document>
<ons:innerElement>someValue</ons:innerElement>
</ons:Document>
</ns:Documents>

XML create node before another PHP

I have a XML file and I'm trying to insert a new node between two others with PHP script.
XML file:
<playlistLog>
<hour>
<track>
<type>take</type>
<url>URL</url>
<title>1473869236.wav</title>
<mix>0</mix>
</track>
(...)
</hour>
</playlistLog>
PHP file:
$xmldoc = new DOMDocument();
$xmldoc->load('../logs/log14-09-2016.xml');
$elem = $xmldoc->getElementsByTagName("track");
$track = $xmldoc->createElement('track');
$type = $xmldoc->createElement('type', 'take');
$track->appendChild($type);
$url = $xmldoc->createElement('url', 'url');
$track->appendChild($url);
$title = $xmldoc->createElement('title', 'title');
$track->appendChild($title);
$mix = $xmldoc->createElement('mix', 'mix');
$track->appendChild($mix);
$xmldoc->documentElement->insertBefore($track,$elem[660]);
$xmldoc->save('../logs/log14-09-2016.xml');
I'm trying to insert the new node before "track" tag number 660 but when I try to open the php file it doesn't work at all.
Can anybody tell me what I am doing wrong?
SOLUTION:
After #ThW response I change a bit what he wrotes and finally the code is doing right:
$document = new DOMDocument();
$document->preserveWhiteSpace = FALSE;
$document->load('../logs/log14-09-2016.xml');
$xpath = new DOMXpath($document);
$previousTrack = $xpath->evaluate('/playlistLog/hour/track')->item(659);
$newTrack = $previousTrack->parentNode->insertBefore($document->createElement('track'),$previousTrack);
$newTrack
->appendChild($document->createElement('type'))
->appendChild($document->createTextNode('take'));
$document->formatOutput = TRUE;
echo $document->save('../logs/log14-09-2016.xml');
$elem[660] is the 661st element node with the tag name track. But its parent node is not the document element. Here is another hour ancestor between. The node you're providing to insertBefore() has a different parent then the node you're adding the new element to.
You can use the $parentNode property to make sure that you append to that node.
Additionally I suggest using Xpath to fetch the track node.
$xml = <<<'XML'
<playlistLog>
<hour>
<track>
<type>take</type>
<url>URL</url>
<title>1473869236.wav</title>
<mix>0</mix>
</track>
</hour>
</playlistLog>
XML;
$document = new DOMDocument();
$document->preserveWhiteSpace = FALSE;
$document->loadXml($xml);
$xpath = new DOMXpath($document);
$previousTrack = $xpath->evaluate('/playlistLog/hour/track[1]')->item(0);
$newTrack = $previousTrack
->parentNode
->insertBefore(
$document->createElement('track'),
$previousTrack
);
$newTrack
->appendChild($document->createElement('type'))
->appendChild($document->createTextNode('take'));
$document->formatOutput = TRUE;
echo $document->saveXml();

Create a XML document using the DOM object with white characters

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();

Categories