【发布时间】:2015-04-24 15:52:30
【问题描述】:
假设我有一个如下的 XML -
$xml = '<?xml version="1.0"?>
<step number="9">
<s_name>test</s_name>
<b_sel>12345</b_sel>
<b_ind>7</b_ind>
</step>';
我希望将其转换为对象,但是当我执行以下步骤时,它会为我提供如下 stdclass 对象 [我将其分配给 $stepInformation 变量] -
$xml = json_decode(json_encode((array) simplexml_load_string($xml)), 1);
$stepInformation = stdClass Object
(
[@attributes] => Array
(
[number] => 9
)
[s_name] => test
[b_sel] => 12345
[b_ind] => 7
)
所以当我在 php 函数中解析这个 stdclass 对象时
function convertStepInformationToArray($stepInformation)
{
$dom = new DOMDocument();
$stepInfo = "{$stepInformation->s_name}{$stepInformation->b_sel}{$stepInformation->b_ind}";
$dom->loadXML("<document>" . $stepInfo . "</document>");
$domx = new DOMXPath($dom);
$entries = $domx->evaluate("//step");
return $entries;
}
我得到的输出是
DOMNodeList Object
(
[length] => 0
)
我希望[length] => 1 继续我的项目。我知道问题出在<step number="9">,在将其转换为对象后如下所示。
stdClass Object
(
[@attributes] => Array
(
[number] => 9
)
注意- 我什至尝试了以下步骤,但没有运气:
$xml = simplexml_load_string($xml);
$stepInformation = SimpleXMLElement Object
(
[@attributes] => Array
(
[number] => 9
)
[s_name] => test
[b_sel] => 12345
[b_ind] => 7
)
你们能否给我一些指示,我怎样才能得到如下输出?只要我得到准确的输出,任何替代方法都可以 -
DOMNodeList Object
(
[length] => 1
)
对此的任何帮助将不胜感激。
谢谢。
【问题讨论】:
-
当您已经可以解析来自
SimpleXML对象的值时,您是否有任何特殊原因需要使用json_encode/decode? -
刚刚更新了我的问题。我什至用过 SIMpleXML,但没有运气。
-
$stepInformation 中的记录不提供 stdClass 对象输出。您已在
(array) simplexml_load_string($xml)中写入数组,并且您正在像对象一样获取$stepInformation->s_name。 -
要将 SimpleXML 对象转换为 DOM 对象,只需使用
dom_import_simplexml- 它甚至不必重新处理 XML,因为它们在内部都使用相同的表示。 (还有一个simplexml_import_dom也可以返回。) -
@hakre 它们完全是不同的问题。 stackoverflow.com/q/29818820/367456 用于从 XML 内容中获取 OCI-Lob 对象。这个问题是用于将 XML 转换为 stdclass/SimpleXML 对象。
标签: php xml simplexml domdocument