xml:lang parse in PHP

前端 未结 5 1305
余生分开走
余生分开走 2020-12-10 19:05

  
    
      
        FW&         


        
相关标签:
5条回答
  • 2020-12-10 19:20

    Has been answered before:

    $dom =new DOMDocument;
    $dom->loadXML( $xml );
    $xPath = new DOMXPath( $dom );
    $nodes = $xPath->query( '/answer/describe/data/code[@xml:lang = "en"]' );
    foreach( $nodes as $node ) {
        echo $node->nodeValue; 
    }
    

    Alternative without XPath:

    $dom =new DOMDocument;
    $dom->loadXML ($xml );
    foreach( $dom->getElementsByTagName( 'code' ) as $node ) {
        if( $node->getAttribute( 'xml:lang' ) === 'en') {
            echo $node->nodeValue;
        }
    }
    
    0 讨论(0)
  • 2020-12-10 19:22

    XPath has a special construct for dealing with xml:lang attribute:

    $xml = new SimpleXMLElement($strXML);
    $data = $xml->describe->data[0];
    $elCode = $data->xpath("code[lang('en')]"); // returns array of SimpleXMLElement
    assert(count($elCode)==1);
    $code_en = (string) $elCode[0];
    

    P.S. greetings to the Sirena ;)

    0 讨论(0)
  • 2020-12-10 19:28

    Thanks. I use this method:

    $XMLObj = new SimpleXMLElement($XML);
    print_r($XMLObj->xpath('/answer/describe/data/code[@xml:lang = "en"]'));
    
    0 讨论(0)
  • 2020-12-10 19:32

    Have a look at the PHP SAX parser decribed here.

    0 讨论(0)
  • 2020-12-10 19:39

    Yes, SimpleXML works but try adding the xml namespace if you run into trouble.

    E.g.:

    <?php
    $xmlstr = <<<XML
    <?xml version="1.0" encoding="UTF-8"?>
    <answer xmlns:xml="http://www.w3.org/XML/1998/namespace">
        <describe data="aircompany">
          <data>
            <code xml:lang="ru">ФВ</code>
            <code xml:lang="en">FW</code>
          </data>
          <data>
            <code xml:lang="ru">УТ</code>
            <code xml:lang="en">UT</code>
          </data>
        </describe>
    </answer>
    XML;
    
    $xml = new SimpleXMLElement($xmlstr);
    
    foreach ($xml->xpath('//data/code[@xml:lang="en"]') as $code) {
        echo $code, '<br/>', PHP_EOL;
    }
    ?>
    
    0 讨论(0)
提交回复
热议问题