如何获得在PHP中的XML标记阵列内的文本(How to get inner text in a x

2019-11-01 11:23发布

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

我想的是将其转换为这样的:$汽车[“奥迪”] [0] [“A1”]等,但我不知道如何让内部文本有入标签(例如:F12 )。 我用的方式simplexml的努力!

所以,现在我这样做:

$doc = new SimpleXmlElement($xml, LIBXML_DTDLOAD); 
$brands = $doc->xpath('//brand[@model="Audi"]');
$model_1 = $brands[0]->model[0];

当然还有没有反应?

Answer 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>';
?>


Answer 2:

尝试这个 :

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

你的错误:

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

$models = $doc->xpath('//cars/brand[@name="Audi"]/*[1]');
var_dump((string)current($models));


Answer 3:

<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>";


Answer 4:

确定这样的伎俩是要转换为字符串标签的时候当然迭代和重复它!

(字符串)$模式;

原来如此! 我认为这是空的,因为调试器未归我任何东西,当我检查它。

您的所有问题正确的工作,非常感谢你!



文章来源: How to get inner text in a xml tag array in php