可能重复:
php count xml elements
我有一个包含视频标题的XML文件
<videolist>
<video>
<title>Title1</title>
</video>
<video>
<title>Title2</title>
</video>
</videolist>
如何计算视频元素的数量?我通常使用simpleXML来读取XML文件。从上面的例子中,有几个视频元素。
答案 0 :(得分:3)
$s = simplexml_import_dom($dom);
echo count($s -> video);
答案 1 :(得分:1)
以下是使用SimpleXML对象的'video'属性的count()示例。
我还包含了一个函数,用于将simpleXML对象转换为可以count()的数组。
<?php
$xml = '
<videolist>
<video>
<title>Title1</title>
</video>
<video>
<title>Title2</title>
</video>
</videolist>
';
$sxe = new SimpleXMLElement($xml);
print count($sxe->video)."\n";
$array = simpleXMLToArray($sxe);
print count($array['video'])."\n";
function simpleXMLToArray($xml,
$flattenValues=true,
$flattenAttributes = true,
$flattenChildren=true,
$valueKey='@value',
$attributesKey='@attributes',
$childrenKey='@children'){
$return = array();
if(!($xml instanceof SimpleXMLElement)){return $return;}
$name = $xml->getName();
$_value = trim((string)$xml);
if(strlen($_value)==0){$_value = null;};
if($_value!==null){
if(!$flattenValues){$return[$valueKey] = $_value;}
else{$return = $_value;}
}
$children = array();
$first = true;
foreach($xml->children() as $elementName => $child){
$value = simpleXMLToArray($child, $flattenValues, $flattenAttributes, $flattenChildren, $valueKey, $attributesKey, $childrenKey);
if(isset($children[$elementName])){
if($first){
$temp = $children[$elementName];
unset($children[$elementName]);
$children[$elementName][] = $temp;
$first=false;
}
$children[$elementName][] = $value;
}
else{
$children[$elementName] = $value;
}
}
if(count($children)>0){
if(!$flattenChildren){$return[$childrenKey] = $children;}
else{$return = array_merge($return,$children);}
}
$attributes = array();
foreach($xml->attributes() as $name=>$value){
$attributes[$name] = trim($value);
}
if(count($attributes)>0){
if(!$flattenAttributes){$return[$attributesKey] = $attributes;}
else{$return = array_merge($return, $attributes);}
}
return $return;
}
答案 2 :(得分:0)
您可以使用只输出一些文本的简单XSLT脚本。 您可以查看PHP provides for XSLT
的各种功能一个简单的脚本看起来像这样:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" encoding="iso-8859-1" indent="no"/>
<xsl:template match="/">
<xsl:value-of select="count(/videolist/video)" />
</xsl:template>
</xsl:stylesheet>
要加载它,您的脚本可能如下所示:
<?php
$yourXMLData = '<videolist>...</videolist>';
$XSLTScript = '<xsl:stylesheet ... ';
// Load the XML source
$xml = new DOMDocument;
$xml->load($yourXMLData);
$xsl = new DOMDocument;
$xsl->load($XSLTScript);
// Configure the transformer
$proc = new XSLTProcessor;
$proc->importStyleSheet($xsl); // attach the xsl rules
echo $proc->transformToXML($xml);
?>