Php 使用simplexml解析xmldata
我必须解析使用simplexml的xml数据以下是我得到的简单xml对象Php 使用simplexml解析xmldata,php,xml,simplexml,Php,Xml,Simplexml,我必须解析使用simplexml的xml数据以下是我得到的简单xml对象 SimpleXMLElement Object ( [@attributes] => Array ( [version] => 1.2 ) [file] => SimpleXMLElement Object ( [@attributes] => Array
SimpleXMLElement Object
(
[@attributes] => Array
(
[version] => 1.2
)
[file] => SimpleXMLElement Object
(
[@attributes] => Array
(
[source-language] => en
[datatype] => plaintext
[original] => file.ext
)
[body] => SimpleXMLElement Object
(
[trans-unit] => Array
(
[0] => SimpleXMLElement Object
(
[@attributes] => Array
(
[id] => 1
)
[source] => search_term
[target] => %count% result for "%query%" has been found.|%count% results for "%query%" have been found.
[alt-trans] => SimpleXMLElement Object
(
[target] => Hola mundo
)
)
[1] => SimpleXMLElement Object
(
[@attributes] => Array
(
[id] => 2
)
[source] => search_noresults
[target] => Sorry, I found no results for your query on the website.
)
[2] => SimpleXMLElement Object
(
[@attributes] => Array
(
[id] => 3
)
[source] => search_failure
[target] => We are very sorry, but the search service is not available at the moment.
)
[3] => SimpleXMLElement Object
(
[@attributes] => Array
(
[id] => 4
)
[source] => search
[target] => Search
)
[4] => SimpleXMLElement Object
(
[@attributes] => Array
(
[id] => 5
)
[source] => previous
[target] => Prev
)
[5] => SimpleXMLElement Object
(
[@attributes] => Array
(
[id] => 6
)
[source] => next
[target] => Next
)
[6] => SimpleXMLElement Object
(
[@attributes] => Array
(
[id] => 7
)
[source] => Search this site
[target] => Search this site
)
[7] => SimpleXMLElement Object
(
[@attributes] => Array
(
[id] => 8
)
[source] => send
[target] => Send
)
)
)
)
)
当我试图通过以下代码解析数据时,会出现问题
$this->glossary = new SimpleXMLElement($this->text);
foreach($this->glossary->file->body->trans-unit as $transunit)
{
//parsing code
}
我得到一个php错误,因为变量之间不能有“-”,并且我们将trans unit作为对象变量。我们不能更改xml文件,因为它是预定义格式的
我还有一个关于simplexml的问题,我有以下xml单元
<trans-unit id="1">
<source>search_term</source>
<target>%count% result for "%query%" has been found.|%count% results for "%query%" have been found.</target>
<alt-trans>
<target xml:lang='es'>Hola mundo</target>
</alt-trans>
</trans-unit>
搜索词
%已找到“%query%”的计数%result。|“%query%”的计数%result已找到。
霍拉·蒙多
我想从前面定义的foreach循环中的
标记中提取“lang='es'”名称空间。第二个问题:
使用xpath
检索xml:lang
:
$xml = simplexml_load_string($x); // assume XML in $x
$target = (string)$xml->xpath("//target[@xml:lang]")[0];
$lang = (string)$xml->xpath("//target[@xml:lang]/@xml:lang")[0];
注意:需要PHP>=5.4,如果您的PHP版本低于此版本,请告诉我有一个解决方法
请看一下手册中的部分,特别是示例#3。哦,我的天哪,我怎么会错过这一点呢?谢谢,顺便问一下,你能回答我的第二个问题吗