使用SimpleXMLElement将值传递到XML名称空间的PHP变量中

时间:2013-06-16 05:39:30

标签: php xml var-dump

我使用SimpleXMLElement获取XML内容,并且出现了var_dump结果。

示例代码:

$data = new SimpleXMLElement($xml);
$data->registerXPathNamespace('ns','http://endpoint.websitecom/');
$part = $data->xpath("//ns:return");
var_dump($part[0]->children("ns",true));

我的结果:

object(SimpleXMLElement)[4]
  public 'result' => 
    object(SimpleXMLElement)[6]
      public 'result' => 
      object(SimpleXMLElement)[10]
      public 'Code' => string '0' (length=1)

  public 'amount' => string '2020.03' (length=7)
  public 'code2' => string '3934.8' (length=6)
object(SimpleXMLElement)[8]

如何将amount,code2变量传递给PHP变量或数组?

$amount = ?????

$code2 = ????

1 个答案:

答案 0 :(得分:1)

我用流动的xml代码编写了一个测试用例(在你的var_dump上反向工程):

<unknown xmlns:ns="http://endpoint.websitecom/">
 <ns:return>
  <ns:result>
   <ns:result>
    <ns:Code>0</ns:Code>
   </ns:result>
  </ns:result>
  <ns:amount>2020.03</ns:amount>
  <ns:code2>3934.8</ns:code2>
 </ns:return>
</unknown>

我在此处编写了此代码,以获取$amount$code2

$data = new SimpleXMLElement($xml);
$data->registerXPathNamespace('ns','http://endpoint.websitecom/');
$part = $data->xpath("//ns:return");
$branch=$part[0]->children("ns",true);
var_dump($branch); // your current output

$amount=$branch->amount;
$code2 =$branch->code2;