创建一个xml文件:
<book id="1">
<chapter id="1">
...
</chapter>
<chapter id="2">
...
</chapter>
<chapter id="3">
...
</chapter>
</book>
我如何计算内部的节点......? 在上面的例子中,函数应该转为3,因为存在三个节点。
注意: 我访问...所以:
$xpath = new DOMXPath($filename);
$book = $xpath->query("//book[@id='1']")->item(0);
答案 0 :(得分:1)
你可以这样做:
参考:http://de2.php.net/manual/en/book.dom.php
<script>
// set variables outside initMap() function to make them visible for other functions
var waypts = [];
var directionsService;
var directionsDisplay;
var map;
// add waypoints
waypts.push({
location: "winnipeg, mb",
stopover: true
});
waypts.push({
location: "spokane, wa",
stopover: true
});
function initMap() {
// map setup
directionsService = new google.maps.DirectionsService;
directionsDisplay = new google.maps.DirectionsRenderer;
map = new google.maps.Map(document.getElementById('map'), {
zoom: 6,
center: {lat: 41.85, lng: -87.65}
});
directionsDisplay.setMap(map);
// calculate route
calculateAndDisplayRoute(directionsService, directionsDisplay);
}
function calculateAndDisplayRoute(directionsService, directionsDisplay) {
directionsService.route({
origin:"Boston, MA",//document.getElementById('start').value,
destination: "San Francisco, CA",//document.getElementById('end').value,
waypoints: waypts,
optimizeWaypoints: true,
travelMode: 'DRIVING'
}, function(response, status) {
if (status === 'OK') {
directionsDisplay.setDirections(response);
var route = response.routes[0];
var summaryPanel = document.getElementById('directions-panel');
summaryPanel.innerHTML = '';
// For each route, display summary information.
for (var i = 0; i < route.legs.length; i++) {
var routeSegment = i + 1;
summaryPanel.innerHTML += '<b>Route Segment: ' + routeSegment +
'</b><br>';
summaryPanel.innerHTML += route.legs[i].start_address + ' to ';
summaryPanel.innerHTML += route.legs[i].end_address + '<br>';
summaryPanel.innerHTML += route.legs[i].distance.text + '<br><br>';
}
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
function removewaypoint(idx=0) {
// this function takes index of location to remove
// point A is start
// point B has index 0
// point C has index 1...
// removewaypoint(1) - will remove point C
waypts.splice(idx, 1);
// recalculate route with new waypoints
calculateAndDisplayRoute(directionsService, directionsDisplay);
}
</script>
除非您可以使用此:
$dom->getElementsByTagName('chapter')->length;
答案 1 :(得分:0)
试试此代码
function xml2array($xmlObject, $out = array()) {
foreach ((array) $xmlObject as $index => $node)
$out[$index] = ( is_object($node) ) ? xml2array($node) : $node;
return $out;
}
$a = '<book>
<chapter id = "1">
...
</chapter>
<chapter id = "2">
...
</chapter>
<chapter id = "3">
...
</chapter>
</book>';
$a = simplexml_load_string($a);
$array=xml2array($a);
echo count($array['chapter']);
修改强>
使用DOMXpath
试试这个
echo $book = $xpath->query("//book[@id='1']/chapter")->length;