XML新行通过PHP无法正常工作

时间:2012-11-12 03:08:17

标签: php html xml dom line

我正在尝试让PHP保存XML文件,同时使用新行来组织它。我尝试使用$dom->formatOutput = true;,但我一直收到此错误:

Warning: DOMDocument::loadXML() [domdocument.loadxml]: Empty string supplied as input in /public_html/rejectlist/processForm.php on line 48

这是我的PHP文件:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Adding Songs...</title>
<style type="text/css">
em {
    text-align:center;
}
</style>
</head>
<body>
<p>
<?
$songs = Array();
function start_element($parser, $name, $attrs){
    global $songs;
    if($name == "song"){
        array_push($songs, $attrs);
    }
}
function end_element ($parser, $name){}
$playlist_string = file_get_contents("playlist.xml");
$parser = xml_parser_create();
xml_set_element_handler($parser, "start_element", "end_element");
xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
xml_parse($parser, $playlist_string) or die("Error parsing XML document.");
print "<br />";
if($_POST['action'] == "ins"){
    array_push($songs, Array(
                "title" => $_POST['name'],
                "artist" => $_POST['artist'],
                "path" => $_POST['path']));
    $songs_final = $songs;
}else if($_POST['action'] == "del"){
    $songs_final = Array();
    foreach($songs as $song){
        if($song['title'] != $_POST['name']){
            array_push($songs_final, $song);
        }
    }
}
$write_string = "<songs>";
foreach($songs_final as $song){
    $write_string .= "<song title=\"$song[title]\" artist=\"$song[artist]\" path=\"$song[path]\" />";
}
$write_string .= "</songs>";
$dom = new DomDocument();
$dom->loadXML($songs);
$dom->formatOutput = true;
$formatedXML = $dom->saveXML();
$fp = fopen("playlist.xml", "w+");
fwrite($fp, $write_string) or die("Error writing to file");
fclose($fp);
print "<em>Song inserted or deleted successfully :)</em><br />";
print "<a href=\"index.php\" title=\"return\">Return</a>";
?>
</p>
</body>
</html>

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

您的代码令人不快阅读,所以我不确定它还有什么问题,但您错误的原因是这一行:

$dom->loadXML($songs);

$songs是一个数组,而不是一个字符串。 (阅读并注意错误信息。)