这是我的PHP代码,用于使用SimpleXML和DOM从URL读取XML,以更改一些参数并将其显示在网页上
我正在阅读的提要位于http://tinyurl.com/boy7mr5
<?php
$xml = simplexml_load_file('http://www.abc.com');
$doc = new DOMDocument();
$doc->formatOutput = true;
$r = $doc->createElement( "All_Products" );
$doc->appendChild( $r );
foreach( $xml as $Product)
{
$b = $doc->createElement( "Product" );
$doc->appendChild( $b );
foreach($Product as $prname=>$value)
{
$prname1 = $doc->createElement( $prname );
$prname1->appendChild(
$doc->createTextNode( $value )
);
$b->appendChild($prname1);
if($prname=='ProductName')
{
$ProductURL = $doc->createElement( "ProductURL" );
$ProductURL->appendChild(
$doc->createTextNode('http://www.abc.com/'.$Product->ProductName.'-p/'.$Product->ProductCode .'.htm' )
);
$b->appendChild( $ProductURL );
}
if($prname=='Categories'){
foreach($value as $catname=>$catvalue)
{
$c = $doc->createElement( "Category" );
$doc->appendChild( $c );
foreach($catvalue as $catname1=>$catvalue1)
{
// echo $catname1."==".$catvalue1;
$catname12 = $doc->createElement( $catname1);
$catname12 ->appendChild(
$doc->createTextNode(htmlspecialchars_decode($catvalue1) )
);
$c->appendChild( $catname12);
}
$prname1->appendChild( $c );
}
}
}
$r->appendChild( $b );
}
echo $doc->saveXML();
?>
最后一行按原样打印所有XML,但它显示了垃圾数据,正如您在这个url中看到的那样http://tinyurl.com/bty8286.
我希望数据看起来像这样http://tinyurl.com/boy7mr5在浏览器中,我应该在代码
这是Content-Type
HTTP标头的问题。第二个链接使用application/xml
,而第一个链接使用php的默认text/html
。您可以使用header()函数更改php脚本的HTTP标头。
header('content-type: application/xml');
编辑:
我已经能够获取原始输入,只有标头无法使其工作(至少在firefox中),在第48580行出现解析错误,这是因为没有对DOMDocument
对象设置编码,而原始输入在utf-8中。带
$doc = new DOMDocument('1.0', 'utf-8');
应该起作用。