I was wondering if it is possible to open an xml file as a plain text file so I can read in each line and manipulate the text?
+3
A:
$xml_file = '/var/www/file.xml';
$contents = file_get_contents($xml_file); // Dumps the entire file into a single string
$contents = file($xml_file); // Dumps each line into an array
However, I would recommend using simplexml_load_file()
(even though you said you wanted to avoid it) because there is no guarantee as to how the xml will be formatted. It could all be on a single line or formatted with line-breaks in unexpected places.
Mike B
2009-10-27 22:53:14
I would like to use simplexml_load_file() but I can't figure out how to use it all that well. My biggest problem is extracting data from a single node. I can never tell when an object is an array of objects or if its a object or a value in the object so I think I gonna stick with your example above right now and branch out a little later. Thanks for your help.
TheGNUGuy
2009-10-28 00:30:19
is_array() , is_object() , is_string()
Mike Valstar
2009-10-28 01:34:39
+1
A:
Why not use any of the XML parser/manipulator directly?
You can find those references at http://www.php.net/manual/en/refs.xml.php
If you have a nicely formatted XML file then,
$file = 'file.xml';
// get contents and normalize the newline
$xml_arr = file($file);
foreach($xml_arr as &$line){
// do your manipulation to $line
}
$ctns = implode("\n",$xml_arr);
file_put_contents($file,$ctns); // write back
thephpdeveloper
2009-10-27 22:59:03
Why to split file context by `\r\n` if you can read file as line array by `file` function?
Ivan Nevostruev
2009-10-27 23:00:44
A:
To read file as array of strings use file
function:
$lines = file('your_xml_file.xml');
foreach($lines as $line) {
## do the stuff for each line
}
Ivan Nevostruev
2009-10-27 22:59:26