问题
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>
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...
回答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>';
?>
回答2:
try this :
//cars/brand[@name="Audi"]/*[1]
Your Errors:
- attribute matching should be
@name="Audi"
*[1]
is the first child node
Example
$models = $doc->xpath('//cars/brand[@name="Audi"]/*[1]');
var_dump((string)current($models));
回答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;
}
I have made this example even more cool:
<?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>";
回答4:
Ok so the trick was to convert to string the tag when the iteration and of course iterate it!
(string)$model;
that was it! i thought it was empty because the debugger didn't return me anything when i inspected it.
All your questions worked right, thank you very much!
来源:https://stackoverflow.com/questions/14504544/how-to-get-inner-text-in-a-xml-tag-array-in-php