0

首先,对不起我的英语。

所以,我有一个包含很多节点的 XML,比如:

   <first>
      <second>
         <third/>
         <fourth/>
      </second>
      <fifth>
          <sixth>
             <seventh/>
          </sixth>
      </fifth>
    </first>

我有一个对象,例如:对象{第三:“asd”,第四:“asdasd”,第七:“asdasdasd”}

如何运行 XML 的所有节点,而不考虑它们的父节点,并用对象中现有属性的值填充每个节点?

4

1 回答 1

1

这是一种使用SimpleXML的方法:

<?php
$object = (object) array(
    'third'   => 'asd',
    'fourth'  => 'asdasd',
    'seventh' => 'asdasdasd'
);

$xml = <<<XML
<first>
    <second>
        <third />
        <fourth />
    </second>
    <fifth>
        <sixth>
            <seventh />
        </sixth>
    </fifth>
</first>
XML;

$sxe = new SimpleXMLElement($xml);

foreach ($object as $key => $value) {
    $node            = $sxe->xpath("//*[./{$key}]");
    $node[0]->{$key} = $value;
}

echo $sxe->asXML();

输出:

<?xml version="1.0"?>
<first>
    <second>
        <third>asd</third>
        <fourth>asdasd</fourth>
    </second>
    <fifth>
        <sixth>
            <seventh>asdasdasd</seventh>
        </sixth>
    </fifth>
</first>
于 2013-05-16T18:19:36.983 回答