PHP DOM generated XML break line [duplicate] - php

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
PHP XML how to output nice format
I have the following PHP DOM code that creates a XML document in a dynamic way:
<?php
// create doctype
$dom = new DOMDocument("1.0");
// display document in browser as plain text
// for readability purposes
header("Content-Type: text/plain");
for ($i=1;$i<=5;$i++)
{
// create root element
$root = $dom->createElement("toppings");
$dom->appendChild($root);
// create child element
$item = $dom->createElement("item");
$root->appendChild($item);
// create text node
$text = $dom->createTextNode("pepperoni");
$item->appendChild($text);
}
// save and display tree
echo $dom->saveXML();
?>
The PHP code generates the next XML code:
<?xml version="1.0"?>
<toppings><item>pepperoni</item></toppings>
<toppings><item>pepperoni</item></toppings>
<toppings><item>pepperoni</item></toppings>
<toppings><item>pepperoni</item></toppings>
<toppings><item>pepperoni</item></toppings>
I would like to know what to change in order for the XML look like this other way:
<?xml version="1.0"?>
<toppings>
<item>pepperoni</item>
</toppings>
<toppings>
<item>pepperoni</item>
</toppings>
<toppings>
<item>pepperoni</item>
</toppings>
<toppings>
<item>pepperoni</item>
</toppings>
<toppings>
<item>pepperoni</item>
</toppings>

Try $dom->formatOutput = true.

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.

update child node xml php from another child

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>

PHP XML - Convert XML node attribute to just a node [duplicate]

This question already has answers here:
How to convert XML attributes to text nodes
(3 answers)
Closed 7 years ago.
I want to write a PHP script that will modify my XML file.
I have my productId within the node as an attribute and I want to parse the entire file and convert it to a separate node. So I want to read the attribute of the node and put that attribute in its own node. But the rest of the nodes will stay as is.
Before:
<product id="123">
<name>bob</name>
<lastname>tim</lastname>
</product>
To:
<product>
<id>123</id>
<name>bob</name>
<lastname>tim</lastname>
</product>
Can I do this in PHP? Bearing in mind the file will have over one thousand separate products in it.
You could do it this way.
$xml = new SimpleXMLElement('<product id="123"></product>');
if(!empty($xml['id'])) {
$xml->addChild('id', $xml['id']);
unset($xml['id']);
}
echo $xml->asXML();
Output:
<?xml version="1.0"?>
<product><id>123</id></product>
Here's the manual's link and the addchild functions link. http://php.net/manual/en/class.simplexmlelement.php
http://php.net/manual/en/simplexmlelement.addchild.php
Update:
If you had multiple products you could loop like this.
$xml = new SimpleXMLElement('<proudcts><product id="123"></product><product id="234"></product></proudcts>');
foreach($xml as $key => $data){
if(!empty($data['id'])) {
$data->addChild('id', $data['id']);
unset($data['id']);
}
}
echo $xml->asXML();
Output:
<?xml version="1.0"?>
<proudcts><product><id>123</id></product><product><id>234</id></product></proudcts>

How to add attribute to xml header using SimpleXMLElement [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Getting SimpleXMLElement to include the encoding in output
PHP :
$xml = new SimpleXMLElement("<Title0></Title0>");
$xml->Title1='Some Text 1';
$output = $xml->asXML('mak.xml');
XML Output :
<?xml version="1.0"?>
<Title0>
<Title1>Some Text 1</Title1>
</Title0>
But I want to add attrbute like encoding="utf-8" to xml header , so that I can have something like this :
<?xml version="1.0" encoding="utf-8" ?>
<Title0>
<Title1>Some Text 1</Title1>
</Title0>
I dont want to use find and replace sort of things on the output file.
Read this:--
http://php.net/manual/en/simplexml.examples-basic.php
try this:-
Example #10 Adding elements and attributes
<?php
include 'example.php';
$movies = new SimpleXMLElement($xmlstr);
$character = $movies->movie[0]->characters->addChild('character');
$character->addChild('name', 'Mr. Parser');
$character->addChild('actor', 'John Doe');
$rating = $movies->movie[0]->addChild('rating', 'PG');
$rating->addAttribute('type', 'mpaa');
echo $movies->asXML();
?>

Hide XML declaration in files generated using PHP

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>

Categories