所以我有一个像这样的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>
我想要的是将此转换为:$ cars ['Audi'] [0] ['A1']等等,但我不知道如何将内部文本放入标签中(例如:F12)。我顺便尝试使用simplexml!
所以,现在我正在这样做:
$doc = new SimpleXmlElement($xml, LIBXML_DTDLOAD);
$brands = $doc->xpath('//brand[@model="Audi"]');
$model_1 = $brands[0]->model[0];
当然没有任何事情发生......
答案 0 :(得分:1)
<cars>
<brand name="Audi">
<model>A1</model>
<model>A3</model>
<model>A5</model>
</brand>
</cars>
$cars = simplexml_load_file("cars.xml"); // root tag cars
// echo $cars->brand[0]['name'];
foreach ($cars->brand[0]->model as $model) {
echo $model;
}
我让这个例子变得更酷:
<?php
echo "<head><style>html,body{padding:0;margin:0;background-color:black;text-align:center;}.ul{border-bottom:10px dashed #555555;width:50%;margin-left:25%;margin-right:25%;list-style-type:none;box-shadow:0px 0px 2px gold;}.li{font-size:100px;background-color:silver;color:white;font-family:arial;text-shadow:1px 1px black;}.li:nth-child(even){background-color:yellow;}</style></head><body>";
$cars = simplexml_load_file("cars.xml"); // root tag cars
// echo $cars->brand[0]['name'];
foreach($cars->brand as $brand) {
echo "<div class='ul'>";
foreach($brand->model as $model) {
echo "<div class='li'>";
echo $model;
echo "</div>";
}
echo "</div>";
}
echo "</body>";
答案 1 :(得分:1)
试试这个:
//cars/brand[@name="Audi"]/*[1]
你的错误:
@name="Audi"
*[1]
是第一个子节点实施例
$models = $doc->xpath('//cars/brand[@name="Audi"]/*[1]');
var_dump((string)current($models));
答案 2 :(得分:1)
<?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>';
?>
答案 3 :(得分:0)
好的,所以诀窍就是在迭代时将标签转换为字符串,然后迭代它!
(字符串)$模型;
那就是它!我认为它是空的,因为我检查时调试器没有返回任何东西。你所有的问题都是正确的,非常感谢你!