你可以试试
$final = array();
$filename = "log.txt";
$news = simplexml_load_file($filename);
foreach ( $news as $item ) {
$item = trim($item);
$content = array();
foreach ( explode("\n", $item) as $info ) {
list($title, $data) = explode(":", $info);
$content[trim($title)] = $data;
}
$final[trim($content['Category'])][] = $content;
}
#Remove Street Food
unset($final['Street Food']);
#Output The Rest
var_dump($final);
输出
array
'New Laws' =>
array
0 =>
array
'Title' => string ' News from Washington' (length=21)
'Author' => string ' John Doe' (length=9)
'Category' => string ' New Laws' (length=9)
'Body' => string ' News content...' (length=16)
'Road Accidents' =>
array
0 =>
array
'Title' => string ' News from Texas' (length=16)
'Author' => string ' General Lee' (length=12)
'Category' => string ' Road Accidents' (length=15)
'Body' => string ' News content/' (length=14)
'School Projects' =>
array
0 =>
array
'Title' => string ' News from Illinois' (length=19)
'Author' => string ' Robert Simpson' (length=15)
'Category' => string ' School Projects' (length=16)
'Body' => string ' News content' (length=13)
您还可以Rewrite The XML
使用以下
#Rewrite the array to new XML Fromat
rewriteToXML($final,"log.xml");
这将返回
<?xml version="1.0"?>
<items>
<item>
<Title> News from Washington</Title>
<Author> John Doe</Author>
<Category> New Laws</Category>
<Body> News content...</Body>
</item>
<item>
<Title> News from Texas</Title>
<Author> General Lee</Author>
<Category> Road Accidents</Category>
<Body> News content/</Body>
</item>
<item>
<Title> News from Illinois</Title>
<Author> Robert Simpson</Author>
<Category> School Projects</Category>
<Body> News content</Body>
</item>
</items>
阅读新格式更容易
$final = array();
$filename = "log.xml";
$news = simplexml_load_file($filename);
foreach ( $news as $item ) {
#Check if not Street Food
if(trim($item->Category) != 'Street Food')
$final[trim($item->Category)][] = (array) $item;
}
#Output The Rest
var_dump($final);
重写功能
function rewriteToXML($array, $fileName = null) {
$xml = new SimpleXMLElement("<items />");
foreach ( $array as $key => $item ) {
$child = $xml->addChild("item");
foreach ( $item as $list ) {
foreach ( $list as $title => $data )
{
$child->addChild($title, $data);
}
}
}
$xml->asXML($fileName);
}