XML foreach SimpleXMLElement

时间:2018-04-05 10:48:25

标签: php curl soap

我想阅读<areaCalda>标记中的所有值。我试过这种方式,但它不起作用。

这是我的xml:

<soap:....>
<listaStatoPS xmlns="http://stato.ps.ws.model.rc.nec">

<StatoPSWS>
<anagraficaPS>...</anagraficaPS>
<esitoRichiesta>...</esitoRichiesta>
<statoPS>
<areePS>
<AreaPS><areaCalda>true</areaCalda></AreaPS>
<AreaPS><areaCalda>false</areaCalda></AreaPS>
<AreaPS><areaCalda>false</areaCalda></AreaPS>
<AreaPS><areaCalda>true</areaCalda></AreaPS>
<AreaPS><areaCalda>true</areaCalda></AreaPS>
</areePS>
</statoPS>
</StatoPSWS>

<StatoPSWS>
<anagraficaPS>...</anagraficaPS>
<esitoRichiesta>...</esitoRichiesta>
<statoPS>
<areePS>
<AreaPS><areaCalda>false</areaCalda></AreaPS>
<AreaPS><areaCalda>false</areaCalda></AreaPS>
<AreaPS><areaCalda>false</areaCalda></AreaPS>
<AreaPS><areaCalda>true</areaCalda></AreaPS>
<AreaPS><areaCalda>false</areaCalda></AreaPS>
</areePS>
</statoPS>
</StatoPSWS>

</listaStatoPS>
<uuid xmlns="http://...">...</uuid>
</ns1:out>
</ns1:getStatoPSResponse>
</soap:Body>
</soap:Envelope>

我的剧本:foreach ($sxe->xpath('//listaStatoPS:StatoPSWS')没关系!

$sxe = new SimpleXMLElement($xml);
$sxe->registerXPathNamespace('listaStatoPS', 'http://stato.ps.ws.model.rc.nec');
foreach ($sxe->xpath('//listaStatoPS:StatoPSWS') as $item) // this WORK!
{


    $data->registerXPathNamespace('listaStatoPS', 'http://stato.ps.ws.model.rc.nec');
    $el2 = $data->xpath('//listaStatoPS:StatoPSWS:areePS:AreaPS'); 

    foreach ($el2 as $val) // not work!
    {
    ...
    }



}

谢谢

1 个答案:

答案 0 :(得分:0)

当您只阅读areaCalda值时,您可以使用类似的内容。

$xml = new SimpleXMLElement(file_get_contents("test.xml"));
foreach ($xml->xpath("//areaCalda") as $item){
    var_dump($item);
}

不要用于下一个路径:,您必须使用/

$sxe = new SimpleXMLElement($xml);
$sxe->registerXPathNamespace('listaStatoPS', 'http://stato.ps.ws.model.rc.nec');
foreach ($sxe->xpath('//listaStatoPS/StatoPSWS') as $item) 
{
    $data->registerXPathNamespace('listaStatoPS', 'http://stato.ps.ws.model.rc.nec');
    $el2 = $item->xpath('//statoPS/areePS/AreaPS/areaCalda'); 

    foreach ($el2 as $val) 
    {
        ...
    }

}

它应该可行