我正在尝试解析xml文件并以不同的顺序打印项目,并在其间使用其他文本。 xml文件是这样的
<list>
<item>
<price>200</price>
<title>Title1</title>
<description>something here</description>
</item>
<item>
<price>350</price>
<title>Title2</title>
<description>something there</description>
</item>
</list>
我希望输出完全像这样,2个不同的行:
"Title1","something here","","200","1",""
"Title2","something there","","350","1",""
看引号和逗号很重要。
我正在使用它,但这还不够。我不知道接下来要做什么......
<?php
//Initialize the XML parser
$parser=xml_parser_create();
//Function to use at the start of an element
function start($parser,$element_name,$element_attrs)
{
switch($element_name)
{
case "PRICE":
echo """;
break;
case "TITLE":
echo """;
break;
case "DESCRIPTION":
echo """;
}
}
//Function to use at the end of an element
function stop($parser,$element_name)
{
echo "",";
}
//Function to use when finding character data
function char($parser,$data)
{
echo $data;
}
//Specify element handler
xml_set_element_handler($parser,"start","stop");
//Specify data handler
xml_set_character_data_handler($parser,"char");
//Open XML file
$fp=fopen("shopmania_ro.xml","r");
//Read data
while ($data=fread($fp,4096))
{
xml_parse($parser,$data,feof($fp)) or
die (sprintf("XML Error: %s at line %d",
xml_error_string(xml_get_error_code($parser)),
xml_get_current_line_number($parser)));
}
//Free the XML parser
xml_parser_free($parser);
?>
提前谢谢。
我有另一个代码
<?php
$xfile = "file.xml";
$xparser=xml_parser_create();
xml_set_character_data_handler($xparser, "cdataHandler");
if(!($fp=fopen($xfile,"r")))
{
die ("File does not exist");
}
while($data=fread($fp, 4096))
{
if(!xml_parse($xparser,$data,feof($fp)))
{
die("XML parse error: xml_error_string(xml_get_error_code($xparser))");
}
}
xml_parser_free($xml_parser);
function cdataHandler($xparser, $cdata)
{
echo "$cdata";
}
?>
,输出
200 Title1 something here 350 Title2 something there
我不知道如何提取数据并以我想要的方式打印它。有帮助吗? 对不起,我是新手......
答案 0 :(得分:1)
显然是 XSLT 样式表语言的用途。将XML文档转换为不同的格式。 PHP附带 XSL 扩展名,非常易于使用。也有例子。
修改强>
如果这对你的目的来说太过分了,你应该看看PHP的SimpleXML扩展,它允许你像使用对象一样使用节点。
编辑2
$xmlstr = <<<XML
<?xml version='1.0' standalone='yes'?>
<list>
<item>
<price>200</price>
<title>Title1</title>
<description>something here</description>
</item>
...
</list>
XML;
$xml = simplexml_load_string($xmlstr);
$list = $xml->list;
foreach ( $list->item as $item ) {
// Not sure if this works, but if it doesn't, substitute the sprintf
// with plain string concatenation
echo sprintf(
'"%s","%s","","%d","1",""',
$item->title,
$item->description,
$item->price
);
}