[Solved] XML: How to convert plan text into XML using php?

XML, Perl, Python, and other languages can be discussed here, even if it isn't PHP (We might forgive you).

Moderator: General Moderators

User avatar
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

Post by Ollie Saunders »

I wanted to convert it into XML document, echo it out just to test it, i'm not wanting to echo the statement out only
In that case how about:

Code: Select all

$line = "<$field>$content</$field>";
However. the output isn't the intended one.
Yeah browsers will do that. You should serve the file as XML:

Code: Select all

header('Content-type: text/xml');
phpwalker
Forum Commoner
Posts: 81
Joined: Sun Apr 23, 2006 12:18 pm

Post by phpwalker »

There's error.
XML Parsing Error: not well-formed
Location: http://localhost/outputDATA.xml
Line Number 3, Column 2:<1> abc aaa
-^
When I try it in Uni, it works. When I try it at home, it doesn't.
Uni platform Win XP Pro, Apache 2.0.X, PHP 5.0.X, IE6, Portable Apps Mozilla;
Home platform Win XP Home, Apache 2.2.X, PHP 5.2.X, IE7, Mozilla 2.0.0.1.

The XML view source is like this.

Code: Select all

<?xml version="1.0" ?>
<doc>
<1> abc aaa
</1><2> def
</2><3> ghi</3></doc>
I know each time when it loops, the abc aaa will consist of a newline at the end, that's why the </1> goes to the next line. For the last content, <3>, it doesn't go to next line, so i can show properly. How do I omit that newline together with the content stored in the variable?

So that I can get,

Code: Select all

<1>abc aaa</1>
<2>def</2>
<3>ghi</3>
Thanks a million for the help.
phpwalker
Forum Commoner
Posts: 81
Joined: Sun Apr 23, 2006 12:18 pm

Post by phpwalker »

In php.net manual, I found this.

Code: Select all

function file2($filename) {
       $fp = fopen($filename, "rb");
       $buffer = fread($fp, filesize($filename));
       fclose($fp);
       $lines = preg_split("/\r?\n|\r/", $buffer);
       return $lines;
}
The following function can handle text files whose line endings are whatever <LF> (*nix), <CR><LF> (M$) or <CR> (Mac)

Code: Select all

//you can use
$file = array_map('rtrim',file('myfile.txt'));
to remove annoying ending lines of the resulting array.
The first method, I tried but don't know how it works, then I try the second method, I tried and it works. The output of the html is:

Code: Select all

<?xml version="1.0" ?>
<doc>
<1> abc aaa</1>
<2> def</2>
<3> ghi</3>
</doc>
However, the XML still give me the error message:
XML Parsing Error: not well-formed
Location: http://localhost/outputDATA.xml
Line Number 3, Column 2:<1> abc aaa</1>
-^
What's the problem!! Anyone could tell me?
Post Reply