如何在php中的xml标记数组中获取内部文本 [英] How to get inner text in a xml tag array in php
本文介绍了如何在php中的xml标记数组中获取内部文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我有一个像这样的xml:
So i have an xml like this:
<cars>
<brand name="Audi">
<model>A1</model>
<model>A3</model>
<model>A5</model>
</brand>
<brand name="Ferrari">
<model>F12</model>
<model>FF</model>
</brand>
</cars>
我想要将其转换为:$ cars ['Audi'] [0] ['A1']等等,但是我不知道如何获取标签中的内部文本(例如:F12)。我正在尝试使用simplexml!
And what i want is to convert this to this: $cars['Audi'][0]['A1'] and so, but i don't know how to get the inner text there is into the tags (example: F12). I'm trying with simplexml by the way!
因此,现在我正在这样做:
So, for now i'm doing this:
$doc = new SimpleXmlElement($xml, LIBXML_DTDLOAD);
$brands = $doc->xpath('//brand[@model="Audi"]');
$model_1 = $brands[0]->model[0];
当然什么也没发生...
And of course nothing happens...
推荐答案
<?php
$xml = '<cars>
<brand name="Audi">
<model>A1</model>
<model>A3</model>
<model>A5</model>
</brand>
<brand name="Ferrari">
<model>F12</model>
<model>FF</model>
</brand>
</cars>';
$doc = simplexml_load_string($xml);
foreach ($doc->children() as $brand) {
foreach ($brand->children() as $model) {
$cars[(string)$brand->attributes()->name][] = (string)$model;
}
}
echo '<pre>';
print_r($cars);
echo '</pre>';
?>
这篇关于如何在php中的xml标记数组中获取内部文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文