【发布时间】:2014-02-03 01:58:18
【问题描述】:
我有一个后端脚本 (getData.php),它与 AJAX 脚本一起使用,以便在更改特定文件的时间戳时更新浏览器,作为长轮询的一种手段。在轮询 .txt 文件时,我已经让脚本工作了,因为它只是将文本逐字回显到浏览器。但是,现在我正在尝试轮询一个我不想逐字回显的 XML 文件;正如您在下面的脚本中看到的那样,我正在尝试识别父节点和子节点,并在合适的地方使用其他 HTML 元素来回显它们。
<?php
$filename = dirname(__FILE__).'/data.xml';
$lastmodif = isset($_GET['timestamp']) ? $_GET['timestamp'] : 0;
$currentmodif = filemtime($filename);
while ($currentmodif <= $lastmodif) {
usleep(10000);
clearsatcache();
$currentmodif = filemtime($filename);
}
$response = array();
$response['msg'] = SimpleXMLElement(file_get_contents($filename));
$response['timestamp'] = $currentmodif;
$data = json_encode($response);
// Print the text portions to extract
foreach ($data['range']['item'] as $book)
{
echo "<div>Book: {$book['bookname']}<p>{$book['text']}</p></div>\n";
}
// Print the array
echo "<pre>";
print_r($data);
echo "</pre>";
?>
请记住,当我只是 echo json_encode($response); 时,脚本正在处理文本文件,但现在我正在制作变量 $data = json_encode($response);,然后使用 print_r($data); 它不起作用。有什么想法吗?
这是我的示例 XML 文件:
<library>
<book>
<bookname>Beowulf</bookname>
<text>This is fake, enter real text here. </text>
</book>
<book>
<bookname>Old Yeller</bookname>
<text>This is fake, enter real text here. </text>
</book>
<book>
<bookname>White Fang</bookname>
<text>This is fake, enter real text here. </text>
</book>
</library>
【问题讨论】:
-
$data 后 json_encode 是一个对象,不再是一个数组,这就是为什么你的循环不起作用。
-
您没有正确使用 simplexmlelement:php.net/manual/en/class.simplexmlelement.php
-
@zeflex 感谢您的输入,但这并不能说明根本原因或与问题相关。如何定位特定节点并回显它们?感谢您的反馈,尽管我会努力清理语法。