【问题标题】:php DOMDocument levelsphp DOMDocument 级别
【发布时间】:2021-07-10 23:12:52
【问题描述】:
<?php

// include db config 
require("config.php"); 

// Start XML file, create parent node
$dom = new DOMDocument("1.0");

$node = $dom->createElement("path");
$parnode = $dom->appendChild($node);

// Select all the rows in the link table
$query = "select * from mytable";
        
$result = mysqli_query($con,$query);

header("Content-type: text/xml");

// Iterate through the rows, adding XML nodes for each

while ($row = @mysqli_fetch_assoc($result)){

  $node = $dom->createElement("link");
  $newnode = $parnode->appendChild($node);
  $newnode->setAttribute("name", $row['siteName']); 
  $newnode->setAttribute("lat", $row['latitude']);
  $newnode->setAttribute("lng", $row['longitude']);
}

echo $dom->saveXML();
?>

上面的代码生成xml

<path>
    <link name="howard" lat="54.36603" lng="-8.51472"/>
    <link name="ramesh" lat="53.8458" lng="-8.3919"/>
    <link name="paula" lat="54.84487" lng="-8.87309"/>
    <link name="rita" lat="51.43692" lng="-9.42123"/>
</path> 

如何在 xml 中再添加一层以生成下面的 xml?

<paths>
    <path>
        <link name="howard" lat="54.36603" lng="-8.51472"/>
        <link name="ramesh" lat="53.8458" lng="-8.3919"/>
        <link name="paula" lat="54.84487" lng="-8.87309"/>
        <link name="rita" lat="51.43692" lng="-9.42123"/>
    </path>
</paths>

【问题讨论】:

    标签: php xml dom


    【解决方案1】:

    你是对的 :-) 来晚了

    现在有效

            <?php
        
        // include db config 
        require("config.php"); 
       
    // Start XML file, create parent node
    $dom = new DOMDocument("1.0");
    
    $node_root = $dom->createElement("paths");
    $pathadd = $dom->appendChild($node_root);
    
    $node2 = $dom->createElement("path");
    $parnode = $pathadd->appendChild($node2);
        
        // Select all the rows in the link table
        $query = "select * from mytable";
                
        $result = mysqli_query($con,$query);
        
        header("Content-type: text/xml");
        
        // Iterate through the rows, adding XML nodes for each
        
        while ($row = @mysqli_fetch_assoc($result)){
        
          $node = $dom->createElement("link");
          $newnode = $parnode->appendChild($node);
          $newnode->setAttribute("name", $row['siteName']); 
          $newnode->setAttribute("lat", $row['latitude']);
          $newnode->setAttribute("lng", $row['longitude']);
        }
        
        echo $dom->saveXML();
        ?>
    

    【讨论】:

    • 您的解决方案只产生一个级别
    • 你是对的 :-) 现在工作已经很晚了
    • 不错的一个!谢谢
    猜你喜欢
    • 1970-01-01
    • 2012-01-10
    • 2013-06-16
    • 2011-02-20
    • 1970-01-01
    • 1970-01-01
    • 2011-07-26
    • 1970-01-01
    相关资源
    最近更新 更多