Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

xml - Unable to add Attribute with Namespace Prefix using PHP Simplexml

Trying to edit an XML document that uses Excels XML-Namespaces:

<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" 
          xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet">

I need to get to this result (need the ss: prefix befire Type):

<Cell ...><Data ss:Type="String">value</Data></Cell>

I've looked over the question Unable add namespace with PHPs SimpleXML but this method is not helping here. In other words, running this as outlined there

$data = $cells[$i]->addChild('Data','value'); 
$data->addAttribute("ss:Type","String","urn:schemas-microsoft-com:office:spreadsheet");

gives me

<Cell ...><Data Type="String">value</Data></Cell>

without the ss: prefix. And if I remove the urn: prefix, then I'm getting this

<Cell ...><Data xmlns:ss="schemas-microsoft-com:office:spreadsheet" ss:Type="String">value</Data></Cell>

In either case, when I open the document with Excel, the data is invisible. With urn: the ss: is missing and without urn: the definition becomes part of the element which is not working in Excel.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you want to add an attribute with a specific namespace prefix w/o adding the namespace to the document, you have to specify not only the prefix in the name parameter, but also prefix it again with xmlns, in my example: xmlns:ss:Type. The namespace URI (third parameter) then will be ignored as well, so it is not necessary either:

$data->addAttribute("xmlns:ss:Type", "String");

Note the xmlns: in front of ss:Type. The output then is as required:

<Cell><Data ss:Type="String">value</Data></Cell>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...