读取子元素的属性

时间:2015-12-01 09:34:20

标签: php xml simplexml

我正在尝试在以下xml中读取location的值:

<service name="xyz">
     <documentation>gSOAP 2.7.11 generated service definition</documentation>
     <port name="xyz" binding="tns:xyz">
      <SOAP:address location="http://192.168.0.222:8092"/>
     </port>
</service>

我正在尝试访问SOAP:address代码但无法:

$wsdlFile = file_get_contents('./wyz.wsdl');

    if($wsdlFile) {
        $xml = simplexml_load_string($wsdlFile);
        foreach( $xml->service->documentation->port->attributes() as $a => $b) {
            echo $a . '-' . $b;
        }
    }

我怎样才能获得location的价值?

2 个答案:

答案 0 :(得分:0)

//Convert to Array like this
$wsdlFile = file_get_contents('./wyz.wsdl');
if($wsdlFile) {
    $wsdlData = json_decode(json_encode($wsdlFile),TRUE);
}
//Now you can access the address through the key=> value pair
$location = $wsdlData['location'];

答案 1 :(得分:0)

在属性中使用:会使获取该属性变得更加困难,但是可能:

按索引:

$value = $xml->port->children()[0]->attributes()['location']->__toString();

或按名称:

$prop = 'SOAP:address';
$value = $xml->port->$prop->attributes()['location']->__toString();

打印SOAP:address及其值的所有属性

$wsdlFile = file_get_contents('./wyz.wsdl');

if($wsdlFile) {
    $xml = simplexml_load_string($wsdlFile);
    $prop = 'SOAP:address';
    foreach($xml->port->$prop->attributes() as $a => $b) {
        echo $a . '-' . $b;
    }
}