PHP: Updating XML from PHP and Saving - php

I'm trying to update 1 particular node in an pre-existing xml file from php. The problem i'm having is that it doesn't seem to be saving to the xml file. Not sure why and any help here will be appreciated!
<?php
$itemNumber = $_GET["itemNumberField"];
$xmlFile = "items.xml";
if(file_exists($xmlFile))
{
// $doc = new DOMDocument('1.0');
// $doc->load($xmlFile);
$doc = DOMDocument::load($xmlFile);
$item = $doc->getElementsByTagName("item");
foreach($item as $node)
{
$itemNumberNode = $node->getElementsByTagName("itemNumber");
$itemNumberNode = $itemNumberNode->item(0)->nodeValue;
$qtyNode = $node->getElementsByTagName("quantity");
$qtyNode = $qtyNode->item(0)->nodeValue;
if ($itemNumberNode == $itemNumber)
{
$qtyNode++;
echo $qtyNode;
}
}
}
else
{
echo "file doesn't exist! <br/>";
}
$doc->save($xmlFile);
?>
Edit: Just to clarify, the adding to the node seems to be fine.
Solution: Turns out the reason it didn't save was because node of the adding. i had to either directly update it or assign an updated value to it.
$qtyNode = $node->getElementsByTagName("quantity");
$qtyNode = $qtyNode->item(0);
...
$qtyNode->nodeValue++;

I've just coded something similar, and found out that $doc->saveXML() just builds up the outgoing xml string. I added a file_put_contents for writing to the xml file and worked fine.
file_put_contents($xmlFile, $doc->saveXML());

You COPY the scalar value (string) into a variable. Then you change the variable.
$qtyNode = $qtyNode->item(0)->nodeValue;
if ($itemNumberNode == $itemNumber)
{
$qtyNode++;
echo $qtyNode;
}
$qtyNode is not a DOMNode object, but a string variable.
You will have to change the DOMNode::$nodeValue property directly or assign the variable to it.
$qtyNode = $qtyNode->item(0);
if ($itemNumberNode == $itemNumber)
{
$qtyNode->nodeValue++;
echo $qtyNode->nodeValue;
}

Chmod the folder in which you want to save xml file: set permissions to maxiamally 775.
If this not works try using Curl

Related

how do i edit compressed gz xml file, compress and save it back, with php? [duplicate]

So, I have this code that searches for a particular node in my XML file, unsets an existing node and inserts a brand new child node with the correct data. Is there a way of getting this new data to save within the actual XML file with simpleXML? If not, is there another efficient method for doing this?
public function hint_insert() {
foreach($this->hints as $key => $value) {
$filename = $this->get_qid_filename($key);
echo "$key - $filename - $value[0]<br>";
//insert hint within right node using simplexml
$xml = simplexml_load_file($filename);
foreach ($xml->PrintQuestion as $PrintQuestion) {
unset($xml->PrintQuestion->content->multichoice->feedback->hint->Passage);
$xml->PrintQuestion->content->multichoice->feedback->hint->addChild('Passage', $value[0]);
echo("<pre>" . print_r($PrintQuestion) . "</pre>");
return;
}
}
}
Not sure I understand the issue. The asXML() method accepts an optional filename as param that will save the current structure as XML to a file. So once you have updated your XML with the hints, just save it back to file.
// Load XML with SimpleXml from string
$root = simplexml_load_string('<root><a>foo</a></root>');
// Modify a node
$root->a = 'bar';
// Saving the whole modified XML to a new filename
$root->asXml('updated.xml');
// Save only the modified node
$root->a->asXml('only-a.xml');
If you want to save the same, you can use dom_import_simplexml to convert to a DomElement and save:
$dom = new DOMDocument('1.0');
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->loadXML($simpleXml->asXML());
echo $dom->saveXML();

replace value in a specific node

I have an XML file and a variable. I want to write a function to replace a specific node's value. Example:
write_xml("->system_settings->settings->hostname",'Helloooooooo');
function write_xml($tag_address, $value) {
$xml = simplexml_load_file("test.xml")
or die("Error: Cannot create object");
$xml->system_settings->settings->hostname = $value;
$xml->asXML("test.xml");
}
In this example, the node ->system_settings->settings if helloooooo should be replaced with hostname.
My problem is: in the above code, I entered the path manually and it works. But if I assign my path dynamically (like below), it doesn't work:
write_xml("->system_settings->settings->hostname",'Helloooooooo');
function write_xml($tag_address, $value) {
...
$xml->$tag_address = $value; // <---- doesn't work
$xml->asXML("test.xml");
}
What should i do?

Failed to show XML Data with PHP Script

I have about 60000 xml files that i have to insert into a MySQL database. so i thought about making a simple php script that would be executed for once to load data from this xml files and insert it into my db on a localhost.
Before inserting it into my DB i tried to show them on the data on the page but it shows nothing, and its type is NULL.
here is the code :
<?php
$dir = new DirectoryIterator('organismes');
foreach ($dir as $fileinfo) {
if (!$fileinfo -> isDot()) {
$XMLFILE = $fileinfo -> getFilename();
echo $XMLFILE . "<br>\n"; /*the filename shows correctly, so the DirectoryIterator is working*/
$pathtofile = "http://localhost/www/organismes/$XMLFILE"; /*the link to the xml file made with a variable*/
echo $pathtofile . "<br>\n"; /* the link shown is correct */
$xml = simplexml_load_file($pathtofile);
echo gettype($xml) . "<br>\n";
if ($xml == FALSE) {
echo "failed to load xml"; /* this message never shows so the xml file loads correctly */
} else {
$Org = $xml->Organisme->Nom; //this variable $Org gets a NULL Value
echo $Org . "<br>" ;
echo gettype($Org);
}
}
}
?>
when i used a print_r($xml), it shows some data so the file loads correctly.
and here is an example of the xml file that i have :
<Organisme id="adil-01053-01" codeInsee="01053" dateMiseAJour="2013-02-27" pivotLocal="adil">
<Nom>Agence</Nom>
<EditeurSource>A2 A3</EditeurSource>
<Adresse type="géopostale">
<Ligne>34, rue du Général-Delestraint</Ligne>
<CodePostal>01000</CodePostal>
<NomCommune>Bourg-en-Bresse</NomCommune>
<Localisation>
<Latitude>46.196535</Latitude>
<Longitude>5.2191997</Longitude>
<Précision>6</Précision>
</Localisation>
<Accessibilité type="ACC"/></Adresse>
<CoordonnéesNum>
<Téléphone>00000000000</Téléphone>
<Télécopie>00000000000</Télécopie>
<Email>adil.01#wanadoo.fr</Email>
<Url>http://www.adil01.org</Url>
</CoordonnéesNum>
<Ouverture><PlageJ début="vendredi" fin="vendredi"><PlageH début="09:00:00" fin="17:00:00"/></PlageJ><PlageJ début="lundi" fin="jeudi"><PlageH début="09:00:00" fin="18:00:00"/></PlageJ>
</Ouverture>
</Organisme>
so i am trying to figure it out why it doesn't show correctly and why it gets a NULL Value
So brothers if you can help that would be wonderful :)
$pathtofile = "http://www.w3schools.com/xml/note.xml";
$xml = simplexml_load_file($pathtofile);
if ($xml == FALSE) {
echo "failed to load xml";
}
else
{
$A = $xml->to;
echo "$A <br />";
}
Focusing on just that part of the code, it seems to work correctly. Either one of two things are happening. The "$xml->Organisme->Nom;" has a spelling error and/or the xml file being pulled does not include those field names.
For testing do
print_r($xml);
right after
echo "$A <br />";
to get an accurate representation of the xml file being pulled.
Hope this helps.
I am not exactly sure what you want but I assume you want to insert XML data into your database. If that's the case, try this:
function create_xml()
{
$xml = simplexml_load_file("file.xml");
$nodes = new SimpleXMLElement('file.xml', null, true)
or die("cannot create");
$i = 0;
foreach ($nodes->children() as $child)
{
$var= $child->xml_child;
$sql = "INSERT INTO ...)";
mysqli_query($connect, $sql);
$i++;
echo "xml set";
}
}

Simplexml_load_file issue, variable gets NULL Value [duplicate]

I have about 60000 xml files that i have to insert into a MySQL database. so i thought about making a simple php script that would be executed for once to load data from this xml files and insert it into my db on a localhost.
Before inserting it into my DB i tried to show them on the data on the page but it shows nothing, and its type is NULL.
here is the code :
<?php
$dir = new DirectoryIterator('organismes');
foreach ($dir as $fileinfo) {
if (!$fileinfo -> isDot()) {
$XMLFILE = $fileinfo -> getFilename();
echo $XMLFILE . "<br>\n"; /*the filename shows correctly, so the DirectoryIterator is working*/
$pathtofile = "http://localhost/www/organismes/$XMLFILE"; /*the link to the xml file made with a variable*/
echo $pathtofile . "<br>\n"; /* the link shown is correct */
$xml = simplexml_load_file($pathtofile);
echo gettype($xml) . "<br>\n";
if ($xml == FALSE) {
echo "failed to load xml"; /* this message never shows so the xml file loads correctly */
} else {
$Org = $xml->Organisme->Nom; //this variable $Org gets a NULL Value
echo $Org . "<br>" ;
echo gettype($Org);
}
}
}
?>
when i used a print_r($xml), it shows some data so the file loads correctly.
and here is an example of the xml file that i have :
<Organisme id="adil-01053-01" codeInsee="01053" dateMiseAJour="2013-02-27" pivotLocal="adil">
<Nom>Agence</Nom>
<EditeurSource>A2 A3</EditeurSource>
<Adresse type="géopostale">
<Ligne>34, rue du Général-Delestraint</Ligne>
<CodePostal>01000</CodePostal>
<NomCommune>Bourg-en-Bresse</NomCommune>
<Localisation>
<Latitude>46.196535</Latitude>
<Longitude>5.2191997</Longitude>
<Précision>6</Précision>
</Localisation>
<Accessibilité type="ACC"/></Adresse>
<CoordonnéesNum>
<Téléphone>00000000000</Téléphone>
<Télécopie>00000000000</Télécopie>
<Email>adil.01#wanadoo.fr</Email>
<Url>http://www.adil01.org</Url>
</CoordonnéesNum>
<Ouverture><PlageJ début="vendredi" fin="vendredi"><PlageH début="09:00:00" fin="17:00:00"/></PlageJ><PlageJ début="lundi" fin="jeudi"><PlageH début="09:00:00" fin="18:00:00"/></PlageJ>
</Ouverture>
</Organisme>
so i am trying to figure it out why it doesn't show correctly and why it gets a NULL Value
So brothers if you can help that would be wonderful :)
$pathtofile = "http://www.w3schools.com/xml/note.xml";
$xml = simplexml_load_file($pathtofile);
if ($xml == FALSE) {
echo "failed to load xml";
}
else
{
$A = $xml->to;
echo "$A <br />";
}
Focusing on just that part of the code, it seems to work correctly. Either one of two things are happening. The "$xml->Organisme->Nom;" has a spelling error and/or the xml file being pulled does not include those field names.
For testing do
print_r($xml);
right after
echo "$A <br />";
to get an accurate representation of the xml file being pulled.
Hope this helps.
I am not exactly sure what you want but I assume you want to insert XML data into your database. If that's the case, try this:
function create_xml()
{
$xml = simplexml_load_file("file.xml");
$nodes = new SimpleXMLElement('file.xml', null, true)
or die("cannot create");
$i = 0;
foreach ($nodes->children() as $child)
{
$var= $child->xml_child;
$sql = "INSERT INTO ...)";
mysqli_query($connect, $sql);
$i++;
echo "xml set";
}
}

Problems with PHP/XML/XSL

I am trying to figure out what I can do to create a code that appends data in my XML file not rewrite the XML file continuously.
I need to be able to save all the form entries and as of right now every time the form is submitted. it creates a new XML file and erases the old one.
This may be really easy to fix or I am just really dumb but I have looked at DOM syntax and do not see what I could change to change the outcome.
// define configuration file name and path
$configFile = 'abook.xml';
// if form not yet submitted
// display form
if (!isset($_POST['submit'])) {
// set up array with default parameters
$data = array();
$data['name'] = null;
$data['email'] = null;
$data['caddress'] = null;
$data['city'] = null;
$data['state'] = null;
$data['zipcode'] = null;
$data['phone'] = null;
$data['pug'] = null;
$data['comment'] = null;
$data['subscribe'] = null;
// read current configuration values
// use them to pre-fill the form
if (file_exists($configFile)) {
$doc = new DOMDocument();
$doc->preserveWhiteSpace = false;
$doc->load($configFile);
$address = $doc->getElementsByTagName('address');
foreach ($address->item(0)->childNodes as $node) {
$data[$node->nodeName] = $node->nodeValue;
}
}
In between is a PHP form and validation code and at the end I use XML tags again:
// generate new XML document
$doc = new DOMDocument();
// create and attach root element <configuration>
$root = $doc->createElement('addressbook');
$configuration = $doc->appendChild($root);
// create and attach <oven> element under <configuration>
$address = $doc->createElement('address');
$configuration->appendChild($address);
// write each configuration value to the file
foreach ($config as $key => $value) {
if (trim($value) != '') {
$elem = $doc->createElement($key);
$text = $doc->createTextNode($value);
$address->appendChild($elem);
$elem->appendChild($text);
}
}
// format XML output
// save XML file
$doc->formatOutput = true;
$doc->save($configFile) or die('ERROR: Cannot write configuration file');
echo 'Thank you for filling out an application.';
}
I am really new at this so I am sorry if my code is pretty messy.
The second part I am dealing with an XSL file which I have linked to my XML file but no matter what syntax I have used to transform, nothing works to save it in a table.
Again, I don't know if this could be caused by the way I have set up my PHP to write the XML.

Categories