我必须解析xml数据我正在使用simplexml以下是我得到的简单xml对象
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>
我想从上面定义的foreach循环中的<alt-trans>
标记中提取“lang ='es'”命名空间。
答案 0 :(得分:0)
使用xml:lang
检索xpath
:
$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&gt; = 5.4,如果您的PHP版本低于此值,请告诉我有解决方法。
在行动中看到它:https://eval.in/98015