【问题标题】:Adding to XML file using PHP with SimpleXML error使用带有 SimpleXML 错误的 PHP 添加到 XML 文件
【发布时间】:2016-11-29 19:25:09
【问题描述】:

我正在使用一个简单的 simplexml php 文件来添加到我的 XML 文件中。由于某种原因,它没有将记录放入 XML 文件中,并且我的日志正在显示

PHP 致命错误:调用成员函数 addChild()

想知道有人可以帮助我吗?可能真的很简单。我附上了 PHP 代码和 XML 文件。

PHP:

<?php
$file = 'news.xml';

$xml = simplexml_load_file($file);

$story = $xml->news->story;

$story->addChild('storyid', '33');
$story->addChild('story_pic', 'images/test.jpg');
$story->addChild('story_title', 'Your Title');
$story->addChild('story', 'This is a test story');
$story->addChild('story_date', '01/01/2001');

$xml->asXML($file);
?>

XML

<?xml version = "1.0" encoding="Windows-1252" standalone="yes"?>
<news>
    <story>
        <storyid>1</storyid>
        <story_pic>http://portfoliotheme.org/enigmatic/wp-content/uploads/sites/9/2012/07/placeholder1.jpg</story_pic>
        <story_title>My Test News Story</story_title>
        <story>fdsfsfsdfdsfdsfsfsdfdsfsfdffsfdssfd</story>
        <story_date>22/01/2016</story_date>
    </story>
    <story>
        <storyid>2</storyid>
        <story_pic>http://portfoliotheme.org/enigmatic/wp-content/uploads/sites/9/2012/07/placeholder1.jpg</story_pic>
        <story_title>My Test News Story2</story_title>
        <story>fdsfsfsdfdsfdsfsfsdfdsfsfdffsfdssfd</story>
        <story_date>22/01/2016</story_date>
    </story>
</news> 

【问题讨论】:

  • 你检查过$story的值吗?

标签: php xml simplexml


【解决方案1】:

当然,这已被确认了数千次,但是:

$file = './news.xml';

$xml = simplexml_load_file($file);
// `$xml` presents root item (`news`) of your xml tree

// add new `story` to your root item (`news`)
$new_story = $xml->addChild('story');

// add items to newly added `$new_story` element
$new_story->addChild('storyid', '33');
$new_story->addChild('story_pic', 'images/test.jpg');
$new_story->addChild('story_title', 'Your Title');
$new_story->addChild('story', 'This is a test story');
$new_story->addChild('story_date', '01/01/2001');

// save as XML
$xml->asXML($file);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-20
    • 2014-05-06
    • 1970-01-01
    • 1970-01-01
    • 2019-01-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多