San*_*dar 0 php xml simplexml domdocument
假设我有一个如下的 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>';
Run Code Online (Sandbox Code Playgroud)
我希望将其转换为对象,但是当我执行以下步骤时,它给了我如下的 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
)
Run Code Online (Sandbox Code Playgroud)
所以当我在 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;
}
Run Code Online (Sandbox Code Playgroud)
我得到的输出是
DOMNodeList Object
(
[length] => 0
)
Run Code Online (Sandbox Code Playgroud)
我想[length] => 1继续我的项目。我知道问题在于将<step number="9">其转换为对象后如下所示。
stdClass Object
(
[@attributes] => Array
(
[number] => 9
)
Run Code Online (Sandbox Code Playgroud)
注意- 我什至尝试过以下步骤但没有运气:
$xml = simplexml_load_string($xml);
$stepInformation = SimpleXMLElement Object
(
[@attributes] => Array
(
[number] => 9
)
[s_name] => test
[b_sel] => 12345
[b_ind] => 7
)
Run Code Online (Sandbox Code Playgroud)
你们能否就此给我一些指示,我怎样才能得到如下输出?任何替代方法都可以,只要我得到确切的输出 -
DOMNodeList Object
(
[length] => 1
)
Run Code Online (Sandbox Code Playgroud)
对此的任何帮助将不胜感激。
谢谢你。
您实际上不需要将SimpleXML对象加载到json_encode/decode.
您已经可以使用该对象并解析您需要的任何值。必须encode/decode作为数组并且必须访问值然后将其转换SimpleXML为太多。
$xml = '<?xml version="1.0"?>
<step number="9">
<s_name>test</s_name>
<b_sel>12345</b_sel>
<b_ind>7</b_ind>
</step>';
$xml = simplexml_load_string($xml);
$step = $xml->xpath('//step');
echo $step[0]->attributes()->number; // 9
echo $xml->s_name, '<br/>', $xml->s_name, '<br/>', $xml->b_ind;
Run Code Online (Sandbox Code Playgroud)
随着DOMDocument独自:
$dom = new DOMDocument;
$dom->loadXML($xml);
$xpath = new DOMXpath($dom);
echo $xpath->evaluate('string(//step/@number)');
Run Code Online (Sandbox Code Playgroud)
保持简单:
$xml = '<?xml version="1.0"?>
<step number="9">
<s_name>test</s_name>
<b_sel>12345</b_sel>
<b_ind>7</b_ind>
</step>';
function convertStepInformationToArray($stepInformation) {
$dom = new DOMDocument();
$dom->loadXML($stepInformation);
$domx = new DOMXPath($dom);
$entries = $domx->evaluate("//step");
return $entries;
}
print_r(convertStepInformationToArray($xml));
Run Code Online (Sandbox Code Playgroud)