从xml文件中删除Name-Space并另存为新XML

时间:2013-03-26 10:07:55

标签: php xml namespaces

这是我获取XML文件的链接: - XML LINK

这是我的代码: -

<?php
function convertNodeValueChars($node) {
    if ($node->hasChildNodes()) {
      foreach ($node->childNodes as $childNode) {
        if ($childNode->nodeType == XML_TEXT_NODE) {
          $childNode->nodeValue = iconv('utf-8', 'ascii//TRANSLIT', $childNode->nodeValue);
        }
        convertNodeValueChars($childNode);         
      }
    }      
  } 

  $doc = new DOMDocument();
  $doc->load('http://services.gisgraphy.com/geoloc/search?lat=13o6&lng=80o12&radius=7000');
  convertNodeValueChars($doc->documentElement);
  $doc->save('general.xml');  
?>

1)我尝试将ASCII字符删除为普通字符
2)想要删除XML文件的名称空间这包含名称空间<results xmlns="http://gisgraphy.com">
3)想要另存为另一个XML文件

1 个答案:

答案 0 :(得分:1)

首先在简单的php文件上创建加载xml从URL: -

<?php
$dom = new DOMDocument();
$dom->load('http://services.gisgraphy.com/geoloc/search?lat=22.298569900000000000&lng=70.794301799999970000&radius=7000', true);
$dom->save('filename.xml');
?>

然后创建一个XSLT文件: -

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"><xsl:output method="xml" version="1.0" encoding="UTF-8" />
        <xsl:template match="*">
                <xsl:element name="{local-name()}">
                        <xsl:apply-templates select="@* | node()"/>
                </xsl:element>
        </xsl:template>
</xsl:stylesheet>

并创建一个php文件来加载xml文件并实现我们的xslt文件: -

<?php
$sourcedoc->load('filename.xml');
    $stylesheet = new DOMDocument();
    $stylesheet->load('new4convert.xsl');
     // create a new XSLT processor and load the stylesheet
    $xsltprocessor = new XSLTProcessor();
    $xsltprocessor->importStylesheet($stylesheet);

    // save the new xml file
    file_put_contents('filename.xml', $xsltprocessor->transformToXML($sourcedoc));
?>

如果你想在一个PHP文件中使用所有的最终总代码: -

<?php
$dom = new DOMDocument();
$dom->load('http://services.gisgraphy.com/geoloc/search?lat=22.298569900000000000&lng=70.794301799999970000&radius=7000', true);
$dom->save('filename.xml');
$sourcedoc = new DOMDocument();
    $sourcedoc->load('filename.xml');
    $stylesheet = new DOMDocument();
    $stylesheet->load('new4convert.xsl');
     // create a new XSLT processor and load the stylesheet
    $xsltprocessor = new XSLTProcessor();
    $xsltprocessor->importStylesheet($stylesheet);

    // save the new xml file
    file_put_contents('filename.xml', $xsltprocessor->transformToXML($sourcedoc));
?>