【问题标题】:Extract value from xml tag从 xml 标签中提取值
【发布时间】:2019-04-24 16:09:27
【问题描述】:

我正在尝试从标签中提取 RecordID = "1014276"

我试过了:

$result = curl_exec($ch);
curl_close($ch);

$xml2 = simplexml_load_string($result);
echo $latitude = (string) $xml2['RecordID'];

这是 XML 响应:

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <soap:Body>
      <ns1:createDataResponse xmlns:ns1="http://3e.pl/ADInterface">
         <StandardResponse RecordID="1014276" xmlns="http://3e.pl/ADInterface"/>
      </ns1:createDataResponse>
   </soap:Body>
</soap:Envelope>

【问题讨论】:

    标签: php xml


    【解决方案1】:

    这不仅仅涉及访问属性,首先您必须选择正确的元素。使用 XPath 是这种结构中注释最多的方式。 由于它为数据定义了一个默认命名空间,因此您需要先将其注册到 SimpleXMLElement(使用 $xml2-&gt;registerXPathNamespace("ns1","http://3e.pl/ADInterface");

    然后您可以使用 XPAth 表达式 //ns1:StandardResponse 找到该元素。由于xpath() 方法返回找到的元素列表,因此使用[0] 仅提取第一个匹配项。然后,您应该能够使用结果元素在代码中提取属性...

    $xml2 = simplexml_load_string($result);
    $xml2->registerXPathNamespace("ns1","http://3e.pl/ADInterface");
    
    $response = $xml2->xpath("//ns1:StandardResponse")[0];
    echo (string) $response['RecordID'];
    

    【讨论】:

      【解决方案2】:

      你可以把它当作

      $xml = '<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
       <soap:Body>
        <ns1:createDataResponse xmlns:ns1="http://3e.pl/ADInterface">
           <StandardResponse RecordID="1014276" xmlns="http://3e.pl/ADInterface"/>
        </ns1:createDataResponse>
       </soap:Body>
      </soap:Envelope>';
      
      $p = xml_parser_create();
      xml_parse_into_struct($p, $xml, $values, $index);
      xml_parser_free($p);
      
      echo $values[3]['attributes']['RECORDID'];
      

      【讨论】:

      • 我用这种方式来获取 标签之间的值 3C68
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-08
      • 1970-01-01
      • 2021-05-06
      相关资源
      最近更新 更多