小编San*_*dar的帖子

在 PHP 中将 XML 转换为对象,然后再次将该对象转换为 XML?

假设我有一个如下的 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 …
Run Code Online (Sandbox Code Playgroud)

php xml simplexml domdocument

0
推荐指数
1
解决办法
1万
查看次数

标签 统计

domdocument ×1

php ×1

simplexml ×1

xml ×1