PHP - Delete last line from xml - php

I have this XML file called help_cat.xml
<?xml version="1.0" encoding="utf-8"?>
<ROOT>
</ROOT>
I want to do something like delete </ROOT> from the XML add new content and give </ROOT> back at the end of the XML file.
But I have the problem with the first step. Delete </ROOT>.
I tried
<?php
$file = "help_cat.xml";
$lines = file($file);
echo sizeof($lines)."<BR />";
$last = sizeof($lines)-1;
echo $lines[$last]."<BR />";
unset($lines[$last]);
?>
The script wrote well that there are 3 rows in the file, but can't delete last row. Could someone help me, please?

Related

Php delete element in xml

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

I want to process a XML file In php

This is my XML file
<?xml version="1.0" encoding="UTF-8"?>
<searchresult>
<query>file</query>
<page-number>3</page-number>
<start>20</start>
<files-per-page>10</files-per-page>
<files-approx-count>6361998</files-approx-count>
<result-files>
<file>
<name>file 1</name>
<description>
descrp
</description>
<url>
http://www.example.com
</url>
</file>
<file>
<name>file 2</name>
<description>
descrp 2
</description>
<url>
http://www.example.com
</url>
</file>
</result-files>
</search-result>
i tried the following code
$xml = simplexml_load_file("file.xml");
foreach ($xml as $xmls):
$name =$xmls->name;
$url =$xmls->url;
echo $name.$url;
endforeach;
but no output please help.
First thing, your XML file is not well-formed. The root tag is <searchresult> while the last tag is </search-result>. This causes a parsing error.
Second thing, if your tags contain dashes, those tags cannot be used directly as variables with SimpleXML, in that case you should use a special syntax (see this: php simplexml_load_file with a dash ( - )). Other way to fix this is, if you control de XML syntax, change the way the XML is written and don't use dashes on tags.
Lastly, I think you want to print out the info of files within the result-files tag.
$xml = simplexml_load_file("file.xml");
foreach ($xml->{'result-files'}->file as $file) {
printFile($file);
}
function printFile($file) {
$name = trim($file->name);
$url = trim($file->url);
print "$name $url\n";
}
Output:
file 1 http://www.example.com
file 2 http://www.example.com
And you are done.
You're creating an object when you use the simplexml_load_file. The object isn't necessarily iterable - but it is indexable by tag names. try not doing the foreach(...) and instead just using echo $xml->name;. If that doesn't work, then perhaps you're looking in the wrong directory for your file. You likely need to do something like:
EDITED TO MATCH XML FILE PROVIDED
$path = $_SERVER['DOCUMENT_ROOT']."/file.xml";
$xml = simplexml_load_file($path);
echo $xml->start; //should output 20

Getting information from more than one large XML file

I am trying to get information from external large xml files; from file 1 (vehicleList.xml) and file 2 (CheckVehicles.xml) into a PHP file. All values in XML file 2 are in XML file 1. I would like to display only values in file 1 that are in XML file 2.
My foreach loop code can bring results for up to 130 items (that is if I reduce the items in XML file 2 to 130 items/nodes). However if I remove the if statement, I am able to get all the 3340 items/vehicles from XML file 1.
Where am I going wrong? I tried arrays but failed.
Here is my code:
//XML FILE 1 with 1300 items
$myXML = new SimpleXMLElement('CheckVehicles.xml', NULL, TRUE);//
foreach($myXML->root->item as $item){
$listArrayNew[(int)$item->value] = (int)$item->value;
}
//XML FILE 2 with 3340 vehicles
$parser = new SimpleXMLElement('vehicleList.xml', NULL, TRUE);
foreach ($parser->GetVehiclesListResponse->GetVehiclesListResult->Vehicle as $Vehicle) {
if($listArrayNew[(int)$Vehicle->ID] == (int)$Vehicle->ID){
$vehicle = $Vehicle->Description;
$regNumber = $Vehicle->RegistrationNumber;
$siteID = $Vehicle->SiteID;
$row .= "<tr>
<td>".$vehicle."</td>
<td>".$regNumber."</td>
<td>".$siteId."</td>
</tr>";
}
}
Here are the XML files:
XML file 1: vehicleList.xml
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope>
<GetVehiclesListResponse>
<GetVehiclesListResult>
<Vehicle>
<ID>153</ID>
<SiteID>11</SiteID>
<GroupID>3</GroupID>
<Description>A.O Basid KAR 459 E</Description>
<RegistrationNumber>KAR 459 E</RegistrationNumber>
</Vehicle>
..............................
<Vehicle>
<ID>3340</ID>
<SiteID>25</SiteID>
<GroupID>4</GroupID>
<Description>UAR 712B White Nissan Tiida (Deus Mubangizi)</Description>
<RegistrationNumber>UAR 712B</RegistrationNumber>
</Vehicle>
</GetVehiclesListResult>
</GetVehiclesListResponse>
</soap:Envelope>
XML file 2: CheckVehicles.xml
<?xml version="1.0" encoding="utf-8"?>
<Result>
<root>
<item>
<index>0</index>
<value>153</value>
</item>
...................
<item>
<index>1300</index>
<value>128</value>
</item>
</root>
</Result>
I don't know where you go wrong in your case. However if you want to select elements from the second file based on a criteria (e.g. an ID / unique Number) from the first file I suggest you make use of xpath in your case:
Obtain the numbers from the first file that are the criteria (e.g. /*/root/item/value)
Select all elements from the second file that match the criteria (e.g. ID in /*/GetVehiclesListResponse/GetVehiclesListResult/Vehicle).
The later point can best be achieved by using the technique outlined in Is there anything for XPATH like SQL “IN”? which is creating a comma separated list of the numbers to select and then compare this against each elements number.
Example:
Consider there 2 500 out of 10 000 elements in a first file and in a second file there are 10 000 elements. Each element can be uniquely identified by it's ID.
The first file has this layout:
<?xml version="1.0"?>
<root>
<item>
<index>0</index>
<id>604</id>
</item>
<item>
<index>1</index>
<id>2753</id>
</item>
...
</root>
And the second file has this layout.
<?xml version="1.0"?>
<list>
<item>
<id>1</id>
<some>Number: 33</some>
</item>
<item>
<id>2</id>
<some>Number: 35</some>
</item>
...
</list>
The xpath query to get all IDs from the first file therefore is:
//item/id
And the query for the second file can be expressed with SimpleXML in PHP as:
$ids = implode(',', $file1->xpath('//item/id'));
$query = '//item[contains(",' . $ids . ',", concat(",", id, ","))]';
You can find example code of that example here: http://eval.in/6370

Pulling a specific field with php out of a xml upload

I've been trying to get the id field to pull and have no idea where I'm going wrong. The rest of the data pulls correctly but I'm trying to add something new to some existing code and everything I've tried hasn't worked. Below is my XML and the PHP code I've been working off of.
I haven't worked with a combo of xml and php before so I could really use a push in the right direction.
<?xml version="1.0" encoding="UTF-8"?>
<enterprise>
<person>
<sourcedid>
<source>Spirit Awards</source>
<id>SP8675309</id>
</sourcedid>
<userid>...</userid>
<name>
<fn>...</fn>
</name>
<email>...</email>
</person>
PHP code:
function get_userid(){
return $this->uid;
}
function __construct($xmlData){
$this->uid = (string)$xmlData->id;
}
SimpleXMLdocs makes this ... well ... simple. The XML you've posted is missing a closing </enterprise> tag. Assuming the XML you're actually parsing includes the closing tag, consider:
$str = '<?xml version="1.0" encoding="UTF-8"?>
<enterprise>
<person>
<sourcedid>
<source>Spirit Awards</source>
<id>SP8675309</id>
</sourcedid>
<userid>...</userid>
<name>
<fn>...</fn>
</name>
<email>...</email>
</person>
</enterprise>
';
$xml = simplexml_load_string($str);
$var = (string) $xml->person->sourcedid->id;
echo $var; // outputs: SP8675309

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