0

我不断收到此代码的错误,即使当我在浏览器中运行它时它应该正常工作,但是当它调用include_once它时由于错误而不起作用

    foreach(($hostlist->uploaded) as $uploaded) {
    if (strcmp($uploaded->url,"http://someurl.com/")==0) {
    $host = simplexml_load_file($config['hostlist']);
    unset($host->uploaded->url);
    unset($host->uploaded->pass);
    $host->uploaded->addChild('url',"http://anotherurl.com/");
    $host->uploaded->addChild('pass',"anotherpass");
    $host->uploaded->asXML($config['hostlist']);
    $host->asXML($config['hostlist']);`
    echo "URL Changed to  http://anotherurl.com/";
    }
  }

知道变量如下:

$config['hostlist'] = 'xml/host.xml';

$hostlist = simplexml_load_file($config['hostlist']);

这是 xml 文件的示例:

<host> 
 <uploaded>
  <work>yes</work>
  <url>http://someurl.com/</url>
  <pass>pass</pass>
 </uploaded>
</host>
4

1 回答 1

1

正如我早先通过评论提到的,您的问题可能是该文件使用相对路径并通过include_once不同文件夹上的脚本访问,这导致您的 XML 的文件路径无效。

这是一个简单的例子,说明您可能会发生什么。

我有以下文件夹结构:

root
  - include_folder/
  - include_folder/read_host.php
  - include_folder/xml
  - include_folder/xml/host.xml
  - test_xml.php

当访问include_folder/read_host.php它读取文件就好了。

这是我的read_host.php

<?php

$config['hostlist'] = 'xml/host.xml';
$hostlist = simplexml_load_file($config['hostlist']);
foreach($hostlist->uploaded as $uploaded)
{
    echo $uploaded->work, "\n";
    echo $uploaded->url, "\n";
    echo $uploaded->pass, "\n";
}

输出:

yes
http://someurl.com/
pass

但是,如果我从中访问test_xml.php具有以下内容:

<?php
include_once('include_folder/read_host.php');
echo "what happens";

它失败并出现错误:

PHP 警告:simplexml_load_file():I/O 警告:无法在第 4 行的 /home/admin/include_folder/read_host.php 中加载外部实体“xml/host.xml” PHP 注意:试图获取非对象的属性/home/admin/include_folder/read_host.php 在第 5 行 PHP 警告:在第 5 行的 /home/admin/include_folder/read_host.php 中为 foreach() 提供的参数无效

发生什么了

但是,如果我更改$config['hostlist'] = 'xml/host.xml';为 XML 文件的绝对路径,它就可以正常工作并输出:

yes
http://someurl.com/
pass
what happens

所以在我的情况下,绝对文件夹是:

$config['hostlist'] = '/home/admin/include_folder/xml/host.xml';
于 2013-08-19T23:16:33.467 回答