问题
This is my PHP code to read XML from a URL using SimpleXML and DOM to change some parameters and show it on a web page
The Feed i am reading is at 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();
?>
The last line prints all the XML as it is but it shows the garbage data as you can see at this url http://tinyurl.com/bty8286.
I want the data to look like this http://tinyurl.com/boy7mr5 in the Browser, what should i change in the code
回答1:
It's a matter of the Content-Type
HTTP header. The second link uses the application/xml
while the first one uses php's default text/html
. You can change your php script's HTTP headers with the header() function.
header('content-type: application/xml');
EDIT:
I've been able to fetch the original input, the only the header doesn't made it work (at least in firefox), got parse error on line 48580, this is due no encoding was set to the DOMDocument
object, while the original input is in utf-8. With
$doc = new DOMDocument('1.0', 'utf-8');
should work.
来源:https://stackoverflow.com/questions/11601974/dom-with-simplexml-doesnt-show-the-data-in-xml-format-in-browser-using-php