【问题标题】:simplexml_load_string loose datasimplexml_load_string 松散数据
【发布时间】:2012-01-07 20:14:10
【问题描述】:

我目前正在使用 file_get_contents 来获取 xml。 它运行良好,当我使用正确的 MIME 类型 header('Content-type: text/xml') 显示 xml 时,我会得到类似这样的东西:

<?xml version="1.0" encoding="iso-8859-1" ?>
<tarification compagnie="banane" cle="laclef">
  <gamme reference="equilibre-sante">
    <tarif formule="f100">Xx.xx</tarif>
    <tarif formule="f200">Xx.xx</tarif>
  </gamme>
</tarification>

要将它用作对象,我使用 simplexml_load_string 但是当我 print_r 返回的对象时,我没有看到公式属性,我只看到这样的内容:

SimpleXMLElement Object
(
  [@attributes] => Array
    (
      [compagnie] => banane
      [cle] => laclef
    )

  [gamme] => Array
    (
      [0] => SimpleXMLElement Object
        (
          [@attributes] => Array
            (
              [reference] => equilibre-sante
            )
          [tarif] => Array
            (
              [0] => Xx.xx
              [1] => Xx.xx
            )
         )
    )
)

我想获取公式属性,我已经测试过按照这个tutorial来做到这一点,但没有成功。

【问题讨论】:

    标签: php xml simplexml


    【解决方案1】:

    您需要将SimpleXMLElement::attributes 用作:

    $xml = simplexml_load_string($xmlstring);    
    foreach($xml->gamme->tarif as $tarif) {
            foreach($tarif->attributes() as $a => $b) {
                    echo $a,'="',$b,"\"\n";
            }
    }
    

    See it

    【讨论】:

    • 备份这个答案。由于某种原因,var_dump 不显示 XML 元素的属性。这是为什么呢?
    • @codaddict 感谢您的帮助
    • 如果您知道属性的键,是否有更直接的方法来获取属性?在php.net/manual/en/simplexmlelement.attributes.php 上,我看到一个示例使用了类似$xml-&gt;attributes("gd",1); 的东西,但我没有找到任何相关文档。
    猜你喜欢
    • 1970-01-01
    • 2014-09-16
    • 2016-12-04
    • 2010-11-28
    • 1970-01-01
    • 1970-01-01
    • 2015-08-20
    • 2017-11-09
    • 2019-05-15
    相关资源
    最近更新 更多