在代码中使用变量而不是整数访问 XML 节点 - 为什么它不使用变量?
Accessing XML node with variable instead of integer in the code - why won't it use a variable?
短篇小说是
这个有效: $xml->person[2]->fullname = $name;
但这不是: $id = $_POST['id']; $xml->person[$id]->fullname=$name;
我需要使用 $id 变量,因为它是通过 html 表单从上一页传递过来的。但是,我不确定为什么无论我做什么它都不起作用,直到我输入实际的整数而不是变量。我的代码有什么问题,为什么这行不通?我还注意到同样的代码(带有变量)在另一个文件中有效,但在这个文件中无效 - 在这里使用变量有什么关系?
以下是一些错误:
Notice: Indirect modification of overloaded element of SimpleXMLElement has no effect in edit.php on line 15
Warning: Creating default object from empty value in /edit.php on line 15
两者略有不同
$xml->person[2]->fullname;
和
$id = $_POST['id'];
$xml->person[$id]->fullname;
不同的是,在第一个示例中,2 是一个数字(整数),而在第二个示例中,$id
是一个字符串。
SimpleXMLElement ArrayAccess 中的字符串(这些 [...]
括号)表示具有字符串名称的属性节点。由于 $id
给出的命名属性不存在,它是 即时创建的 但还不是文档的一部分。因此它不能被修改(例如用 ->
操作)。
有了这些知识,将字符串转换为整数应该可以减轻负担:
$id = (int) $_POST['id'];
$xml->person[$id]->fullname;
干杯。示例:
<?php
/**
* Accessing XML node with variable instead of integer in the code - why won't it use a variable?
*
* @link
*/
$buffer = <<<XML
<doc>
<person><fullname>Sally Stewart</fullname></person>
<person><fullname>Nicole Kidman</fullname></person>
</doc>
XML;
$xml = simplexml_load_string($buffer);
$name = 'Gregory Peck';
$id = (int) '2';
$xml->person[$id]->fullname = $name;
$xml->asXML('php://output');
输出(美化):
<?xml version="1.0"?>
<doc>
<person><fullname>Sally Stewart</fullname></person>
<person><fullname>Nicole Kidman</fullname></person>
<person><fullname>Gregory Peck</fullname></person>
</doc>
短篇小说是
这个有效: $xml->person[2]->fullname = $name;
但这不是: $id = $_POST['id']; $xml->person[$id]->fullname=$name;
我需要使用 $id 变量,因为它是通过 html 表单从上一页传递过来的。但是,我不确定为什么无论我做什么它都不起作用,直到我输入实际的整数而不是变量。我的代码有什么问题,为什么这行不通?我还注意到同样的代码(带有变量)在另一个文件中有效,但在这个文件中无效 - 在这里使用变量有什么关系?
以下是一些错误:
Notice: Indirect modification of overloaded element of SimpleXMLElement has no effect in edit.php on line 15
Warning: Creating default object from empty value in /edit.php on line 15
两者略有不同
$xml->person[2]->fullname;
和
$id = $_POST['id'];
$xml->person[$id]->fullname;
不同的是,在第一个示例中,2 是一个数字(整数),而在第二个示例中,$id
是一个字符串。
SimpleXMLElement ArrayAccess 中的字符串(这些 [...]
括号)表示具有字符串名称的属性节点。由于 $id
给出的命名属性不存在,它是 即时创建的 但还不是文档的一部分。因此它不能被修改(例如用 ->
操作)。
有了这些知识,将字符串转换为整数应该可以减轻负担:
$id = (int) $_POST['id'];
$xml->person[$id]->fullname;
干杯。示例:
<?php
/**
* Accessing XML node with variable instead of integer in the code - why won't it use a variable?
*
* @link
*/
$buffer = <<<XML
<doc>
<person><fullname>Sally Stewart</fullname></person>
<person><fullname>Nicole Kidman</fullname></person>
</doc>
XML;
$xml = simplexml_load_string($buffer);
$name = 'Gregory Peck';
$id = (int) '2';
$xml->person[$id]->fullname = $name;
$xml->asXML('php://output');
输出(美化):
<?xml version="1.0"?>
<doc>
<person><fullname>Sally Stewart</fullname></person>
<person><fullname>Nicole Kidman</fullname></person>
<person><fullname>Gregory Peck</fullname></person>
</doc>