PHP无效字符错误

前端之家收集整理的这篇文章主要介绍了PHP无效字符错误前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
运行此代码时出现此错误
致命错误:test.PHP中带有消息’无效字符错误’的未捕获异常’DOMException’:29堆栈跟踪:#0 test.PHP(29):DOMDocument-> createElement(‘1OhmStable’,’a’)#1 { main}在第29行的test.PHP中抛出

来自原始XML文件的节点确实包含无效字符,但是当我从节点中剥离无效字符时,应该创建节点.我需要在原始XML文档上进行哪种编码?我需要解码saveXML吗?

function __cleanData($c) 
{
    return preg_replace("/[^A-Za-z0-9]/","",$c);
}
$xml = new DOMDocument('1.0','UTF-8');
$xml->load('test.xml');    
$xml->formatOutput = true; 

$append = array();
foreach ($xml->getElementsByTagName('product') as $product ) 
    {
        foreach($product->getElementsByTagName('name') as $name ) 
        {

            $append[] = $name;
        }
                foreach ($append as $a)  
                {
                    $nodeName = __cleanData($a->textContent);

                        $element = $xml->createElement(htmlentities($nodeName),'a');
                }
        $product->removeChild($xml->getElementsByTagName('details')->item(0));
        $product->appendChild($element);
    }

$result = $xml->saveXML();
$file = "data.xml";
file_put_contents($file,$result);

这就是原始XML的样子:

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet href="/v1/xsl/xml_pretty_printer.xsl" type="text/xsl"?>
<products>
<product>
<modelNumber>M100</modelNumber>
<itemId>1553725</itemId>
<details>
  <detail>
    <name>1 Ohm Stable</name>
    <value>600 x 1</value>
  </detail>
 </details>
</product>
 </products>

新文档应该如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet href="/v1/xsl/xml_pretty_printer.xsl" type="text/xsl"?>
<products>
<product>
<modelNumber>M100</modelNumber>
<itemId>1553725</itemId>
  <1 Ohm Stable>

  </1 Ohm Stable>

  </product>
 </products>
您只能使用以数字开头的元素名称
1OhmStable  <-- rename this
_1OhmStable <-- this is fine

php parse xml – error: StartTag: invalid element name

一篇好文章: – http://www.xml.com/pub/a/2001/07/25/namingparts.html

A Name is a token beginning with a letter or one of a few punctuation characters,and continuing with letters,digits,hyphens,underscores,colons,or full stops,together known as name characters.

猜你在找的PHP相关文章