0

所以我有一个这样的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];

当然,什么也没有发生……

4

4 回答 4

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>";
于 2013-01-24T15:30:25.957 回答
1

试试这个 :

//cars/brand[@name="Audi"]/*[1]

你的错误:

  1. 属性匹配应该是@name="Audi"
  2. *[1]是第一个子节点

例子

$models = $doc->xpath('//cars/brand[@name="Audi"]/*[1]');
var_dump((string)current($models));
于 2013-01-24T15:33:44.070 回答
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>';
?>
于 2013-01-24T15:36:32.133 回答
0

好的,所以诀窍是在迭代时将标签转换为字符串,当然还要迭代它!

(字符串)$模型;

就是这样!我认为它是空的,因为当我检查它时调试器没有返回任何东西。

您的所有问题都解决了,非常感谢!

于 2013-01-24T15:43:15.957 回答