运行此代码时我收到此错误:Fatal error: Uncaught exception 'DOMException' with message 'Invalid Character Error' in test.php:29 Stack trace: #0 test.php(29): DOMDocument->createElement('1OhmStable', 'a') #1 {main} thrown in test.php on line 29
原始 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 解析 xml - 错误:StartTag:元素名称无效 https://stackoverflow.com/questions/6588888/php-parse-xml-error-starttag-invalid-element-name
一篇不错的文章:-http://www.xml.com/pub/a/2001/07/25/namingparts.html http://www.xml.com/pub/a/2001/07/25/namingparts.html
名称是以字母或几个标点字符之一开头的标记,并以字母、数字、连字符、下划线、冒号或句号继续,统称为名称字符。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)