data.txt
ha15rs,250,home2.gif,2
ha36gs,150,home3.gif,1
ha27se,300,home4.gif,4
ha4678,200,home5.gif,5
i want convert this textfile into xml using simplexml module using php? thanks :))
p.s. im new to this
EDIT:
<allproperty>
<aproperty>
<postcode></postcode>
<price></price>
<imagefilename></imagefilename>
<visits></visits>
</aproperty>
<aproperty>
<postcode></postcode>
<price></price>
<imagefilename></imagefilename>
<visits></visits>
</aproperty>
<aproperty>
<postcode></postcode>
<price></price>
<imagefilename></imagefilename>
<visits></visits>
</aproperty>
</allproperty>
I will suggest you to use XMLWriter instead, because it is best suited for that (and it's also built-in like SimpleXML):
$fp = fopen('data.txt', 'r');
$xml = new XMLWriter;
$xml->openURI('php://output');
$xml->setIndent(true); // makes output cleaner
$xml->startElement('allproperty');
while ($line = fgetcsv($fp)) {
if (count($line) < 4) continue; // skip lines that aren't full
$xml->startElement('aproperty');
$xml->writeElement('postcode', $line[0]);
$xml->writeElement('price', $line[1]);
$xml->writeElement('imagefilename', $line[2]);
$xml->writeElement('visits', $line[3]);
$xml->endElement();
}
$xml->endElement();
Of course, you can change the php://output argument to a filename if you want it to output to a file.
Although I think XMLWriter is best suited for that task (like in my other answer), if you really want to do it with SimpleXML, here's how:
$fp = fopen('data.txt', 'r');
$xml = new SimpleXMLElement('<allproperty></allproperty>');
while ($line = fgetcsv($fp)) {
if (count($line) < 4) continue; // skip lines that aren't full
$node = $xml->addChild('aproperty');
$node->addChild('postcode', $line[0]);
$node->addChild('price', $line[1]);
$node->addChild('imagefilename', $line[2]);
$node->addChild('visits', $line[3]);
}
echo $xml->saveXML();
You will notice that the output is not as clean: it's because SimpleXML doesn't allow you to automatically indent tags.
Related
I have a large XML file more than 100 MB. I am reading the file in chunks like this
$fp = fopen('large.xml', 'r');
while ($data = fread($fp, 4096)) {
The format of XML is like this
<PersonalInfo>
<UserDetail>
<FirstName>ABC</FirstName>
<Occupation>Student</Occupation>
<DateOfBirth>08/14/1999</DateOfBirth>
</UserDetail>
<CaseDetail>....</CaseDetail>
<TransactionDetail>....</TransactionDetail>
</PersonalInfo>
<PersonalInfo>
<UserDetail>
<FirstName>XYZ</FirstName>
<Occupation>Student</Occupation>
<DateOfBirth>04/25/1991</DateOfBirth>
</UserDetail>
<CaseDetail>....</CaseDetail>
<TransactionDetail>.....</TransactionDetail>
</PersonalInfo>
<PersonalInfo>
<UserDetail>
<FirstName>DEF</FirstName>
<Occupation>Teacher</Occupation>
<DateOfBirth>05/12/1984</DateOfBirth>
</UserDetail>
<CaseDetail>....</CaseDetail>
<TransactionDetail>...</TransactionDetail>
</PersonalInfo>
I want to just include those records where the Occupation TAG is "Student" and write those results to a CSV file.
I have tried the preg_match as
preg_match( "/\(.*?)\</PersonalInfo>/s", $data, $match );
to select the Tags and then look into $match but it is returning double values(repetition).
First check if your xml is valid with the help of following link :
http://www.xmlformatter.net/
If your xml is valid then do following :
$dom = new DOMDocument('1.0', 'UTF-8');
$dom->formatOutput = true;
#$dom->load('large.xml');
$tags = $dom->getElementsByTagName('PersonalInfo');
foreach ($tags as $destination) {
foreach($destination->childNodes as $child) {
if ($child->textContent == "Student") {
echo "Write code to create csv file";
}
}
}
I want to add/display data from querying from the database and add it into an XML file.
Example, I have a table_persons which has a name and age. I create a mysql query to get its name and age. Then simply put the data(name and age of persons) into an XML file.
How would you do that? Or is it possible?
I suggest you use DomDocument and file_put_contents to create your XML file.
Something like this:
// Create XML document
$doc = new DomDocument('1.0', 'UTF-8');
// Create root node
$root = $doc->createElement('persons');
$root = $doc->appendChild($root);
while ($row = mysql_fetch_assoc($result)) {
// add node for each row
$node = $doc->createElement('person');
$node = $root->appendChild($node);
foreach ($row as $column => $value) {
$columnElement = $doc->createElement($column);
$columnElement = $node->appendChild($columnElement);
$columnValue = $doc->createTextNode($value);
$columnValue = $columnElement->appendChild($columnValue);
}
}
// Complete XML document
$doc->formatOutput = true;
$xmlContent = $doc->saveXML();
// Save to file
file_put_contents('persons.xml', $xmlContent);
<?php
[snip] //database code here
$f = fopen('myxml.xml', 'a+');
foreach($row = mysqli_fetch_assoc($resultFromQuery))
{
$str = "<person>
<name>{$row['name']}</name>
<age>{$row['age']}</age>
</person>\n";
fwrite($f, $str);
}
fclose($f);
?>
Assuming you use mysqli, this code works. If not, suit to fit. In the fopen function call, the a+ tells it to open it for reading at writing, placing the pointer at the end of the file.
Best of luck.
I really need some help on an issue: I'm converting an XML to CSV using a PHP script, but the XML contains some + signs and I don't know how to remove them from the CSV.
This is the XML file structure:
<PRICES>
<PRICE>
<WIC>HDE0AAFGRBOX</WIC>
<STOCK>100+</STOCK>
<MY_PRICE>219.00</MY_PRICE>
</PRICE>
</PRICES>
This is the script I use:
<?
$filexml='stock.xml';
if (file_exists($filexml)) {
$xml = simplexml_load_file($filexml);
$f = fopen('stock.csv', 'w')
foreach($xml->PRICES->PRICE as $price) {
fputcsv($f, get_object_vars($price),',','"');
}
fclose($f);
}
?>
The script works fine and the CSV file is good, but because I'm a noob with PHP I don't know how to remove the "+" sign.
Any help will be greatly appreciated.
Thanks in advance!
You could try to trim the chars you want to be removed (the '+' char):
foreach($xml->PRICES->PRICE as $price) {
$price->STOCK = trim($price->STOCK, "+");
fputcsv($f, get_object_vars($price),',','"');
}
Try to use str_replace :
$filexml='stock.xml';
if (file_exists($filexml)) {
$xml = simplexml_load_file($filexml);
$f = fopen('stock.csv', 'w')
foreach($xml->PRICES->PRICE as $price) {
$price->STOCK = str_replace("+","",$price->STOCK);
fputcsv($f, get_object_vars($price),',','"');
}
fclose($f);
}
$fp = fopen('data.txt', 'r');
$xml = new SimpleXMLElement('<allproperty></allproperty>');
while ($line = fgetcsv($fp)) {
if (count($line) < 4) continue; // skip lines that aren't full
$node = $xml->addChild('aproperty');
$node->addChild('postcode', $line[0]);
$node->addChild('price', $line[1]);
$node->addChild('imagefilename', $line[2]);
$node->addChild('visits', $line[3]);
}
echo $xml->saveXML();
im using this script to convert text file into a xml file, but i want to output it to a file, how can i do this simpleXML, cheers
file_put_contents function would do it. The function take a filename and some content and save it to the file.
So retaking your example you would just to replace the echo statement by file_put_contents.
$xml = new SimpleXMLElement('<allproperty></allproperty>');
$fp = fopen('data.txt', 'r');
while ($line = fgetcsv($fp)) {
if (count($line) < 4) continue; // skip lines that aren't full
$node = $xml->addChild('aproperty');
$node->addChild('postcode', $line[0]);
$node->addChild('price', $line[1]);
$node->addChild('imagefilename', $line[2]);
$node->addChild('visits', $line[3]);
}
file_put_contents('data_out.xml',$xml->saveXML());
For the record, you can use asXML() for that. I mean, it's right there in the manual, just read it and your life will get easier. (I assume, perhaps asking StackOverflow for basic stuff is easier for some)
Also, and this one is more circumstantial, you don't necessarily need to use addChild() for every child. If there is no child of that name, it can be assigned directly using the object property notation:
$fp = fopen('data.txt', 'r');
$xml = new SimpleXMLElement('<allproperty />');
while ($line = fgetcsv($fp)) {
if (count($line) < 4) continue; // skip lines that aren't full
$node = $xml->addChild('aproperty');
$node->postcode = $line[0];
$node->price = $line[1];
$node->imagefilename = $line[2];
$node->visits = $line[3];
}
$xml->asXML('data.xml');
Bassicly what I want to do is using PHP open a xml file and edit it using php now this I can do using fopen() function.
Yet my issue it that i want to append text to the middle of the document. So lets say the xml file has 10 lines and I want to append something before the last line (10) so now it will be 11 lines. Is this possible. Thanks
Depending on how large that file is, you might do:
$lines = array();
$fp = fopen('file.xml','r');
while (!feof($fp))
$lines[] = trim(fgets($fp));
fclose($fp);
array_splice($lines, 9, 0, array('newline1','newline2',...));
$new_content = implode("\n", $lines);
Still, you'll need to revalidate XML-syntax afterwards...
If you want to be able to modify a file from the middle, use the c+ open mode:
$fp = fopen('test.txt', 'c+');
for ($i=0;$i<5;$i++) {
fgets($fp);
}
fwrite($fp, "foo\n");
fclose($fp);
The above will write "foo" on the fifth line, without having to read the file entirely.
However, if you are modifying a XML document, it's probably better to use a DOM parser:
$dom = new DOMDocument;
$dom->load('myfile.xml');
$linenum = 5;
$newNode = $dom->createElement('hello', 'world');
$element = $dom->firstChild->firstChild; // skips the root node
while ($element) {
if ($element->getLineNo() == $linenum) {
$element->parentNode->insertBefore($newNode, $element);
break;
}
$element = $element->nextSibling;
}
echo $dom->saveXML();
Of course, the above code depends on the actual XML document structure. But, the $element->getLineNo() is the key here.