首页 > 解决方案 > PHP XML 不使用 SimpleXml 解析

问题描述

我的 xml 没有解析,我不知道为什么第一行 xml 没有解析,但第二行解析好

我知道我错过了代码中的任何内容,但在谷歌中搜索并没有找到正确的答案

// this xml not work, with <soap:Envelope> tags

$string = '<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<GetBrandsListResponse xmlns="http://tempuri.org/">
<GetBrandsListResult>
<DocumentElement>
<BrandLst>
  <ID>1</ID>
  <Name>Audi</Name>
</BrandLst>
  <BrandLst>
    <ID>350</ID>
    <Name>BMW</Name>
  </BrandLst>
  </DocumentElement>
  </GetBrandsListResult>
  </GetBrandsListResponse>
</soap:Body>
</soap:Envelope>';

// but this xml works, without soap envelope tags

$string = '
<BrandLst>
  <ID>1</ID>
  <Name>Audi</Name>
</BrandLst>
';

$xml = simplexml_load_string($string);
var_dump($xml);

标签: phpxmlxsdsimplexmlxml-namespaces

解决方案


通过添加 xpath 和 registerXPathNamespace 修复

$xml = simplexml_load_string($string);
$xml->registerXPathNamespace('default', 'http://tempuri.org/');
$auto = $xml->xpath("//default:BrandLst");

推荐阅读