Unformatted XML parsing using PHP
I have a xml file from a client and it's not formatted well. This xml was generated out of flash and I don't have the source file to add any tags to it.
Is there any way can I open an xml file in PHP, preg_replace
the tags with "something" and show the output.
I tried just php file opening and reading the contents and it shows the output but there is no li开发者_运维技巧ne breaks like that.
Is there any way to read the xml and modify the tags on the fly and then just read file to show the content?
Example xml content - so basically the information is in it's own tag but doesn't have a parent tag like "". Any idea how can I just display all these info ? i want to display
xxxxxx in
yyyyyy in [16:38]mr.xyz:hello[16:38]mr.abc:heyxxxxxx out<?xml version="1.0" encoding="UTF-8"?>
<in>---xxxxxx in---</in>
<in>---yyyyyy in---</in>
<time>[16:38]</time> <user>mr.xyz</user><separator>:</separator> </content>hello</content>
<time>[16:38]</time> <user>mr.abc</user><separator>:</separator> </content>hey</content>
<out>---xxxxxx out--</out>
You could use jQuery-like library to get the values. Here is one http://code.google.com/p/phpquery/wiki/Basics
You could do something like this - and then set the content-type headers to XML using php function header( 'Content-type: text/xml' );
and the browser would serve it as an XML document.
function replaceTag( $tag, $new, $content )
{
if ( !preg_match( '/\<'.$tag.'(.*?)\>(.*?)\<\/'.$tag.'\>/i', $content ) )
{
return FALSE;
}
return preg_replace( '/\<'.$tag.'(.*?)\>(.*?)\<\/'.$tag.'\>/i', "<{$new}$1>$2</{$new}>", $content );
}
echo replaceTag( 'in', 'newIn', '<in>123</in>' ); // Should output <newIn>123</newIn>
EDIT:
I might have misinterpreted the question. If you wish to do something with the data of the XML output, I would refer you to the simplexml
methods within PHP. More information on them can be found here; http://php.net/simplexml
don't use regex for xml parsing.
either use PHPs SimpleXML classes,
http://us3.php.net/manual/en/simplexml.examples-basic.php
and if the xml is not well formed, or you need more advanced functionality, use PHPs DOM classes,
http://www.php.net/manual/en/book.dom.php
either one of these can parse the xml, make edits, and/or output it in a well formatted file.
精彩评论