【问题标题】:Regular Expression for replacing XML Tag用于替换 XML 标记的正则表达式
【发布时间】:2012-09-12 12:11:23
【问题描述】:

我正在尝试替换 xml 中的标签。我已经通过 curl 在变量中存储了一个 xml 结果。并试图制作一个file.xml。 当它

  <Topics>
  <Topic code="Balances" count="26" pagesize="100" />
  </Topics>

使用此函数,它不会返回任何匹配项。为什么?

 function get_tag( $tag, $xml ) {
    $tag = preg_quote($tag);

     preg_match_all('{<'.$tag.'[^>]*>(.*?)</'.$tag.'>}',
               $xml,
               $matches,
               PREG_PATTERN_ORDER);

  return $matches[1];
 }

【问题讨论】:

    标签: php xml regex parsing


    【解决方案1】:

    您的示例是解析文档的一个非常糟糕且缓慢的实现。建议您查看DOMDocument 对象并尝试实现它。

    根据你的例子的基本用法:

    $dom = new DOMDocument();
    $dom->loadXML("<xml ... />"); // Current document
    
    $replace = $dom->getElementsByTagName($tag);
    
    foreach ($replace as $node)
    {
        $xml = $dom->createDocumentFragment();
        $xml->loadXML("<xml ... />"); // XML to replace original with
    
        $dom->replaceChild($xml, $node); // XML is your new node
    }
    
    $dom->normalize(); // Saves the changes
    echo $dom->saveXML(); // Output
    

    编辑;抱歉 - 现在是更好的例子。

    【讨论】:

    • +1 丹尼尔是对的。非常不建议使用正则表达式解析 XML。
    • 您不能在 DocumentFragment 上使用 loadXML。该行:$xml-&gt;loadXML("&lt;xml ... /&gt;"); // XML to replace original with 可以替换为:$xml-&gt;appendXML("&lt;xml ... /&gt;"); // XML to replace original with
    【解决方案2】:

    这是你想要的:

    <?php
    
    $xml = '
    <tag1>
        <tag2>
            x
        </tag2>
        <tag3>
        </tag3>
        <tag2>
            y
        </tag2>
    </tag1>
    ';
    
    function get_tag($tag, $xml){
        $tag = preg_quote($tag);
    
        preg_match_all('/<'.$tag.'.*?>(.*?)<\/'.$tag.'>/s', $xml, $matches, PREG_PATTERN_ORDER);
    
        return $matches[1];
    }
    
    print_r(get_tag('tag2', $xml));
    
    ?>
    

    输出:

    Array
    (
        [0] => 
            x
    
        [1] => 
            y
    
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-08-20
      • 2019-10-16
      • 2013-05-29
      • 2012-11-02
      • 1970-01-01
      • 2021-04-24
      • 1970-01-01
      相关资源
      最近更新 更多