如何在localhost中将数据写入xml?

时间:2016-01-11 10:39:30

标签: php xml database localhost

我正在使用localhost写入数据xml。但它不会写数据。 PHP和XML文件位于同一目录中。当.php执行时,没有回应。我该如何解决这个问题?

Xml文件:

<?xml version="1.0"?>
<Infos>
<Info name="someone" mail="something@gmail.com" />
</Infos>

我的PHP代码:

<?php
$testName = "Stephen"
$testMail = "example@gmail.com"

addInfoToXml(__DIR__ . "/test.xml","Infos","Info",$testName,$testMail);

function addInfoToXml($path,$parent,$child,$name,$mail)
{
    $doc = new DOMDocument();
    $doc->formatOutput = true;
    $doc->preserveWhiteSpace=true;
    $doc->load($path);

    $root = $doc->getElementsByTagName($parent)->item(0);

    $info = $doc->createElement($child);
    $info->setAttribute("adsoyad",$name);
    $info->setAttribute("mail",$mail);
    $info = $root->appendChild($info);

    $doc->save($path);
}

?>

1 个答案:

答案 0 :(得分:0)

除了从@ Raphioly-San提到的声明变量中遗漏分号,你应该使用实际路径而不是url。一些错误检查也可能是一个好主意。

$testName = "Stephen";
$testMail = "example@gmail.com";

addInfoToXml( __DIR__."\test.xml", "Infos", "Info", $testName, $testMail);

function addInfoToXml( $path, $parent, $child, $name, $mail ){
    $path=file_exists( realpath( $path ) ) ? realpath( $path ) : false;
    clearstatcache();

    if( $path ){
        $doc = new DOMDocument();
        $doc->formatOutput = true;
        $doc->preserveWhiteSpace=true;
        $doc->load( $path );

        $root = $doc->getElementsByTagName( $parent )->item(0);
        if( $root ){
            $info = $doc->createElement( $child );
            $info->setAttribute("adsoyad",$name);
            $info->setAttribute("mail",$mail);
            $info = $root->appendChild($info);
            $doc->save($path);
        }
    } else {
        echo "error: incorrect path to xml file";   
    }
}