需要帮助使用PHP删除xml中的子项

时间:2013-11-14 22:38:24

标签: javascript php html xml simplexml

我正在尝试使用php脚本从我的jobs.xml文件中删除子项。

我的jobs.xml看起来像是:

    <jobs>
    <event jobid="1">
    <title>jobtitle</title>
    <desc>description</desc>
    <date>postdate</date>
    </event>
    <event jobid="2">
    <title>jobtitle</title>
    <desc>description</desc>
    <date>postdate</date>
    </event>
    <event jobid="3">
    <title>jobtitle</title>
    <desc>description</desc>
    <date>postdate</date>
    </event>
    </jobs>

我创建了一个php脚本,我从用户那里获取jobid并提交并删除具有该jobid的事件子项。

但问题是,当我创建一个新工作时,我得到一个重复的jobid,因为当我创建新的工作事件时,我使用$ jobid = $ xmlobj-&gt; count()+ 1;

有人可以帮助我。我更喜欢使用php脚本,但java脚本也可以。

编辑:

这是我要删除的代码:

    <?php
    $jobs = simplexml_load_file('jobs.xml');
    $jobid = $_POST['jobid'];
    foreach ($jobs->children() as $event) {
    if($event->attributes()->jobid == $jobid)
    {
        $dom=dom_import_simplexml($event);
    $dom->parentNode->removeChild($dom);
    }
    }
    $jobs->asXML('jobs.xml');
    ?>

2 个答案:

答案 0 :(得分:0)

$jobs = simplexml_load_file('jobs.xml');
$jobid = 1;
foreach ($jobs->children() as $event) {
    if($event->attributes()->jobid == $jobid){
        $dom=dom_import_simplexml($event);
        $dom->parentNode->removeChild($dom);
    }
}

echo $jobs->asXML();

答案 1 :(得分:0)

  

请注意:这仅适用于新创建的文件。现有文件需要在根元素next_jobid="N"上手动添加<jobs>

欢迎进一步改进:

class JobsXML
{
    public function __construct($filename)
    {
        $this->filename = $filename;
        $this->dom = new DOMDocument;
        $this->dom->formatOutput = true;
        @$this->dom->load($filename);
        $this->xpath = new DOMXPath($this->dom);

        if ($this->xpath->query('//jobs')->length == 0) {
            $this->root = $this->dom->createElement('jobs');
            $this->root->setAttribute('next_jobid', 1);
            $this->dom->appendChild($this->root);
        } else {
            $this->root = $this->xpath->query('//jobs')->item(0);
        }
    }

    public function insertEvent($title, $desc, $date)
    {
        $next_jobid = $this->root->getAttribute('next_jobid');
        $event = $this->dom->createElement('event');
        $event->setAttribute('jobid', $next_jobid);
        $event->appendChild($this->dom->createElement('title', $title));
        $event->appendChild($this->dom->createElement('desc', $desc));
        $event->appendChild($this->dom->createElement('date', $date));
        $this->root->appendChild($event);
        $this->root->setAttribute('next_jobid', intval($next_jobid) + 1);
    }

    public function removeEvent($jobid)
    {
        foreach ($this->xpath->query("//event[@jobid=$jobid]") as $node) {
            $node->parentNode->removeChild($node);
        }
    }

    public function save()
    {
        $this->dom->save($this->filename);
    }
}

插入事件:

$jobs = new JobsXML('jobs.xml');
$jobs->insertEvent('jobtitle', 'description', 'postdate');
$jobs->save();

删除事件:

$jobs = new JobsXML('jobs.xml');
$jobs->removeEvent(1);
$jobs->save();