Php delete element in xml - php

I'm trying to use php to delete an xml element but it doesn't work. I tried some different code but no one works. I would also like to use cookies to get element in the future. Can you suggest me what I have to do ? I'm not expert and for this I'm in difficulty.
Here the code:
<?php
$dom = new DOMDocument();
$dom->load("Dati.xml");
$matchingElements = $dom->getElementsByTagName("Matematica");
$totalMatches = $matchingElements->length;
$elementsToDelete = array();
$elementsToDelete[] = $matchingElements->item(0);
foreach ( $elementsToDelete as $elementToDelete ) {
$elementToDelete->parentNode->removeChild($elementToDelete);
}
$dom->save($xmlFileToLoad);
echo "<script type='text/javascript'>";
echo "window.close();";
echo "</script>";
echo "Puoi chiudere questa pagina";
?>
Here the xml:
<?xml version="1.0" encoding="UTF-8"?>
<document>
<Informatica>
<nome>aaaa</nome>
<classe>3C</classe>
<titolo>Informatica</titolo>
<materia>Informatica</materia>
<ISBN>123456789101112</ISBN>
<prezzo>12</prezzo>
<autori>tizio</autori>
<contatto>nanni-lombardo1#hotmail.it</contatto>
<codice>123456</codice>
</Informatica>
<Matematica>
<nome>bbb</nome>
<classe>3C</classe>
<titolo>math</titolo>
<materia>Matematica</materia>
<ISBN>123456789101112</ISBN>
<prezzo>12</prezzo>
<autori>tizio</autori>
<contatto>nanni-lombardo1#hotmail.it</contatto>
<codice>123456</codice>
</Matematica>
</document>

Please be sure to :
Remove the space before your XML start tag
Define your $xmlFileToLoad variable
Make your destination XML writable (see Chmod & permissions)
My test file works fine : https://eu.andredasilva.fr/testandre/test.php (source code : https://eu.andredasilva.fr/testandre/test.php.source)
Base XML : https://eu.andredasilva.fr/testandre/Dati.xml
Result XML : https://eu.andredasilva.fr/testandre/test.xml

Related

How to get attributes of XML root element using SimpleXMLElement

I have an XML file with the root element name wwwjob. This root element contains attributes, I need to access the value of the 'method' attribute to be able to update various database entries.
This is a little bit of a learning curve at the moment.
<?xml version="1.0" encoding="iso-8859-1"?>
<wwwjob id="32cca11IACH" method="Delete">
some more xml stuff
</wwwjob>
Ive tried:
<?php $xml = $vacancyXML->wwwjob['method']; ?>
This just gave me 'NULL'.
Ive also tried:
<?php $xml = $vacancyXML->getName(); ?>
This just spits out the name 'wwwjob'.
I need to store the method (Delete/Update/Add) as a variable for use in later parts of the function.
Thanks
When loadinG to simplexml, attributes of the root element became attributes of the simpleXml object. So, you can get it just
$str = '<?xml version="1.0" encoding="iso-8859-1"?>
<wwwjob id="32cca11IACH" method="Delete">
</wwwjob>';
$vacancyXML = simplexml_load_string($str);
echo $vacancyXML['method']; // Delete
demo
You can get the attributes of the root element with SimpleXMLElement::attributes():
$www = new SimpleXMLElement($xml);
echo $www->attributes()->method; // Delete
Demo

Adding child to XML file using PHP

While adding child, this error is thrown :
Cannot add child. Parent is not a permanent member of the XML tree.
I cannot resolve this.
This is my code :
if($visited=='FIRST')
{
$xml=new SimpleXMLElement("<xml/>");
$topology=$xml->addChild("Topology_Configuration");
$flavor=$topology->addChild("Flavor");
$networks=$topology->addChild("Networks");
$vms=$topology->addChild("VMs");
$vnfs=$topology->addChild("VNFs");
$xml->asXML('saddening.xml');
}
else
{
$xml= simplexml_load_file('saddening.xml');
$Topology_Configuration = new SimpleXMLElement($xml->asXML());
$vmcount=$_POST['arguments']['vmcount'];
$flavor=$Topology_Configuration->Flavor;
$flavor_name=$flavor->addChild($_POST['arguments']['flavorName']);
$Topology_Configuration->asXML('saddening.xml');
}
When it is executed for the first time, the file is created(in if part). Otherwise else part is executed. It cannot add the child and is throwing the error in line :
$flavor_name=$flavor->addChild($_POST['arguments']['flavorNa‌​me']);. Please help!!
The XML from your first run results in an XML like this:
<?xml version="1.0"?>
<xml>
<Topology_Configuration>
<Flavor/>
<Networks/>
<VMs/><VNFs/>
</Topology_Configuration>
</xml>
So if you strip down the problem you can reproduce it with:
$Topology_Configuration = simplexml_load_file($fileName);
$flavor=$Topology_Configuration->Flavor;
$flavor->addChild('abc');
echo $Topology_Configuration->asXml();
Results in:
Warning: SimpleXMLElement::addChild(): Cannot add child.
Parent is not a permanent member of the XML tree in
The message is a little wrong, you just try to add the element to an element that does not exists. $Topology_Configuration contains the xml element node, not the Topology_Configuration.
Here are two possible solutions:
Change the XML structure
Create the XML with the Topology_Configuration as the root element.
$topology =new SimpleXMLElement("<Topology_Configuration/>");
Change the access to the Flavor
$xml = simplexml_load_file($fileName);
$flavor=$xml->Topology_Configuration->Flavor;
$flavor->addChild('abc');
At the first time, you can use example to add child nodes
$new_xml = new SimpleXMLElement("<root></root>");
$new_xml->addAttribute('newAttr', 'value');
$newsIntro = $new_xml->addChild('content');
$newsIntro->addAttribute('type', 'value');
Header('Content-type: text/xml');
echo $new_xml->asXML();
and result
<?xml version="1.0"?>
<news newAttr="value">
<content type="value"/>
</news

Simple xml returns no values when trying to access nodes

Hi guys very new to the php world.
I am listening for a PHP post that contains xml, when the xml is retrieved i need to access individual nodes. I am able to echo the full xml file but not individual attributes.
Currently I am just sending the data using a chrome extension Postman. There is no front end code. Here is my XML:
<?xml version="1.0" encoding="UTF-8"?>
<job>
<job_ref>abc123</job_ref>
<job_title>Test Engineer</job_title>
</job>
And here is my PHP:
if($_SERVER['REQUEST_METHOD'] === 'POST') {
$xml = file_get_contents('php://input');
echo $xml;
$xml=simplexml_load_file($xml);
echo $xml->job_ref . "<br>";
echo $xml->job_title . "<br>";
}else{
die();
}
Any hep wopuld be amazing am I am very stuck.
Many thanks
simplexml_load_file expect PATH to the XML file, not its content. You have to use simplexml_load_string instead:
$xml = simplexml_load_string($xml);

Parsing xml file with .php extension and php header

I have a slight problem. I need to parse a file and populate a web banner with the results. Problem is, the file is called : "_banner_products.php" and it's contents are as follows:
<?php header('Content-Type:text/xml'); ?><?php echo '<?xml version="1.0" encoding="UTF-8"?>'; ?>
<carouselle>
<firstLayer>
<layerName>Leica Disto X310</layerName>
<layerProduct>Disto X310</layerProduct>
<layerPic>http://www.leicaestonia.ee/extensions/boxes_design/flashpics/1334482548.jpg</layerPic>
<layerPrice>0,-</layerPrice>
<layerPriceOld></layerPriceOld>
<layerLink>http://www.leicaestonia.ee/index.php?id=11627</layerLink>
<layerTimer>01.05.2012 00:00</layerTimer>
</firstLayer>
<firstLayer>
.....
.....
</firstLayer>
</carouselle>
How can I loop through this file to group all the "firstLayer" children into one and so on..
If I just use:
$file = fopen("_banner_products.php", "r");
while (!feof($file)){
$line = fgets($file);
}
simplexml_load_file throws this-
"_banner_products.php:1: parser error : Start tag expected, '<' "
Then I only get the contents of the <...> tags meaning there is no way for me to differentiate if I am out of the scope already.
Thanks for anyone responding. If anything is unclear I´ll try to explain more.
EDIT.
Thank you for the solution, indeed using the full URL worked:
simplexml_load_file("http://localhost/MySite/_banner_products.php");
You are having issue because simplexml_load_file is treating your file like a local xml file .. what you need to do is add the full URL
Example
simplexml_load_file("http://localhost/web/_banner_products.php");
Use Case getting layerName for example
_banner_products.php
<?php
header ( 'Content-Type:text/xml' );
echo '<?xml version="1.0" encoding="UTF-8"?>';
?>
<carouselle>
<firstLayer>
<layerName>Leica Disto X310</layerName>
<layerProduct>Disto X310</layerProduct>
<layerPic>http://www.leicaestonia.ee/extensions/boxes_design/flashpics/1334482548.jpg</layerPic>
<layerPrice>0,-</layerPrice>
<layerPriceOld></layerPriceOld>
<layerLink>http://www.leicaestonia.ee/index.php?id=11627</layerLink>
<layerTimer>01.05.2012 00:00</layerTimer>
</firstLayer>
<firstLayer>
<layerName>Leica Disto X310</layerName>
<layerProduct>Disto X310</layerProduct>
<layerPic>http://www.leicaestonia.ee/extensions/boxes_design/flashpics/1334482548.jpg</layerPic>
<layerPrice>0,-</layerPrice>
<layerPriceOld></layerPriceOld>
<layerLink>http://www.leicaestonia.ee/index.php?id=11627</layerLink>
<layerTimer>01.05.2012 00:00</layerTimer>
</firstLayer>
</carouselle>
view details
$xml = simplexml_load_file("http://localhost/lab/stockoverflow/_banner_products.php");
echo "<pre>" ;
foreach($xml as $key => $element)
{
echo $element->layerName , PHP_EOL ;
}
The most obvious way to do this is to strip out the first line, and add the XML declaration back in with your code.
You could also parse the file with PHP, using eval(), but be very sure about what you are parsing, as this could be a very large security hole.

xml and php getting tag elements with certain element and outputting

I am have two xml files.. I first get one and loop through it then I need to take an id from the first xml file and find it in the second one and echo out the results associated with that id. If I were to do this with SQL I would simply do this:
$query = (SELECT * FROM HotelSummary WHERE roomTypeCode = '$id') or die();
while($row=mysql_fetch_array($query)){
$name = $row['Name'];
}
echo $name;
How can I do this is in xml and php??
I recommend you to read the DOMDocument documentation.
It's quite heavy but also powerful (not always clear what happens, but the Internet shold always give you a solution)
You can simply walk through your first document, finding your Id and then find your DOMElement via an XPath.
<?php
$dom = new DOMDocument();
$dom->load('1.xml');
foreach ($dom->getElementsByTagName('article') as $node) {
// your conditions to find out the id
$id = $node->getAttribute('id');
}
$dom = new DOMDocument();
$dom->load('2.xml');
$xpath = new DOMXPath($dom);
$element = $xpath->query("//*[#id='".$id."']")->item(0);
// would echo "top_2" based on my example files
echo $element->getAttribute('name');
Based on following test files:
1.xml
<?xml version="1.0" encoding="UTF-8"?>
<articles>
<article id="foo_1">
<title>abc</title>
</article>
<article id="foo_2">
<title>def</title>
</article>
</articles>
2.xml
<?xml version="1.0" encoding="UTF-8"?>
<tests>
<test id="foo_1" name="top_1">
</test>
<test id="foo_2" name="top_2">
</test>
</tests>
Use SimpleXML to create an object representation of the file. You can then loop through the elements of the Simple XML object.
Depending on the format of the XML file:
Assuming it is:
<xml>
<roomTypeCode>
<stuff>stuff</stuff>
<name>Skunkman</name>
</roomTypeCode>
<roomTypeCode>
<stuff>other stuff</stuff>
<name>Someone Else</name>
</roomTypeCode>
</xml>
It would be something like this:
$xml = simplexml_load_file('xmlfile.xml');
for($i = 0; $i < count($xml->roomTypeCode); $i++)
{
if($xml->roomTypeCode[$i]->stuff == "stuff")
{
$name = $xml->roomTypeCode[$i]->name;
}
}
That connects to the XML file, finds how many roomTypeCode entries there are, searches for the value of "stuff" within and when it matches it correctly, you can access anything having to do with that XML entry.

Categories