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>
Related
This question already has answers here:
How do you parse and process HTML/XML in PHP?
(31 answers)
Closed 8 years ago.
Greetings Everybody & thanks in advance for your answers.
So, my difficulty is this, i found a nice tutorial about a restful web service and i can not manage to modify it to my needs.
The below sample code works like a charm
function get_price($find) {
$products = array(
"test" => 293,
"test2" => 348,
"test3" => 267
);
foreach ($products as $product => $price) {
if ($product == $find) {
return $price;
break;
}}}
The $price return runs correctly for each of the above elements of the array which i choose through a simple html form.
Now my code
function get_tickets($find){
$xml = simplexml_load_file("products.xml");
// Here i want to return some of the xml's elements
}
and the included xml file
<products>
<company>
<name>test</name>
<tel>test</tel>
</company>
<products>
<product id="1">
<name>test</name>
<value>test</value>
<color>test</color>
</product>
</products>
</products>
I want to be able to access all the elements of the xml like the first sample code. Thank you.
The xpath() function should do want you want. It returns an array of elements that match the path given. For example, $xml->xpath("products/products/product") will give you all your product elements.
This question already has an answer here:
Create XML with xmlns:xlink attribute in a node
(1 answer)
Closed 8 years ago.
Thanks for your help, I need php script to generate the following XML
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<design xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="http://anydomain.com">
<name>xxx</name>
<description>yyy</description>
</design>
You could use SimpleXML to create such xml.
Rough example:
$xml = new SimpleXMLElement('<design />'); // set parent node
$xml->addAttribute('xmlns', 'http://anydomain.com'); // attributes
$xml->addAttribute('xlink:ns', '', 'http://www.w3.org/1999/xlink');
unset($xml->attributes('xlink', true)['ns']);
$xml->addChild('name', 'xxx'); // add those children
$xml->addChild('description', 'yyy');
echo $xml->asXML(); // output
Need help with updating some simplexml code I did along time ago. The XML file I'm parsing from is formatted in a new way, but I can't figure out how to navigate it.
Example of old XML format:
<?xml version="1.0" encoding="UTF-8"?>
<pf version="1.0">
<pinfo>
<pid><![CDATA[test1 pid]]></pid>
<picture><![CDATA[http://test1.image]]></picture>
</pinfo>
<pinfo>
<pid><![CDATA[test2 pid]]></pid>
<picture><![CDATA[http://test2.image]]></picture>
</pinfo>
</pf>
and then the new XML format (note "category name" added):
<?xml version="1.0" encoding="UTF-8"?>
<pf version="1.2">
<category name="Cname1">
<pinfo>
<pid><![CDATA[test1 pid]]></pid>
<picture><![CDATA[http://test1.image]]></picture>
</pinfo>
</category>
<category name="Cname2">
<pinfo>
<pid><![CDATA[test2 pid]]></pid>
<picture><![CDATA[http://test2.image]]></picture>
</pinfo>
</category>
</pf>
And below the old code for parsing that doesn't work since the addition of "category name" in the XML:
$pinfo = new SimpleXMLElement($_SERVER['DOCUMENT_ROOT'].'/xml/file.xml', null, true);
foreach($pinfo as $resource)
{
$Profile_id = $resource->pid;
$Image_url = $resource->picture;
// and then some echo´ing of the collected data inside the loop
}
What do I need to add or do completely different? I tried with xpath,children and sorting by attributes but no luck - SimpleXML has always been a mystery to me :)
You were iterating over all <pinfo> elements located in the root element previously:
foreach ($pinfo as $resource)
Now all <pinfo> elements have moved from the root element into the <category> elements. You now need to query those elements first:
foreach ($pinfo->xpath('/*/category/pinfo') as $resource)
The now wrong named variable $pinfo is standing a bit in the way so it better do some more changes:
$xml = new SimpleXMLElement($_SERVER['DOCUMENT_ROOT'].'/xml/file.xml', null, true);
$pinfos = $xml->xpath('/*/category/pinfo');
foreach ($pinfos as $pinfo) {
$Profile_id = $pinfo->pid;
$Image_url = $pinfo->picture;
// ... and then some echo´ing of the collected data inside the loop
}
The category elements exist as their own array when you load the XML file. The XML you are used to parsing is contained within. All you need to do is wrap your current code with another foreach. Other than that there isn't much to change.
foreach($pinfo as $category)
{
foreach($category as $resource)
{
$Profile_id = $resource->pid;
$Image_url = $resource->picture;
// and then some echo´ing of the collected data inside the loop
}
}
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
PHP - How to parse this xml?
Parse xml with php - storing parts into array (close to deletion or already deleted)
If I had the following XML file and I wanted to save the values in the tags name and number into an array called department, how would I be able to do it using PHP?
<?xml version="1.0"?>
<data>
<record id="1">
<department>
<name>ACME</name>
<number>5</number>
</department>
<floor>
<name>ACME Floor</name>
<number>5</number>
</floor>
</record>
</data>
You should use
DOMDocument::loadXML
<?php
$doc = new DOMDocument();
$doc->load('book.xml');
$books = $dom->getElementsByTagName('book');
foreach ($books as $book) {
echo $book->nodeValue, PHP_EOL;
}
?>
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>