如何使用PHP修复XML解析错误?

时间:2012-01-28 22:23:33

标签: php xml

  

可能重复:
  PHP library for parsing XML with a colons in tag names?

我有下面显示的xml,我想解析产品标题。当我使用下面的PHP代码时,我在第5行的/home/content/c/a/s/cashme/html/buylooper/xml.php中得到“解析错误:语法错误,意外”:' strong>“因为”:“位于标签中。我该如何解决这个问题?

*更新:我已经得到了第一部分的答案,但是我在如何解析xml标签的属性方面遇到了麻烦。我遇到问题的标签是“s:images”标签内的“s:image”标签(链接属性)。

    <?php
    $url = 'xml-file.xml';
    $xml = simplexml_load_file($url);
    $title = $xml->entry[0]->s:product->s:title; 
    //print
    echo '<br/>';
    echo $title;
    ?>


  <entry gd:kind="shopping#product"> 
  <s:product> 
   <s:googleId>9400569674928563633</s:googleId> 
   <s:author> 
    <s:name>Amazon.com</s:name> 
    <s:accountId>2860562</s:accountId> 
   </s:author> 
   <s:creationTime>2010-08-19T05:50:21.000Z</s:creationTime> 
   <s:modificationTime>2012-01-26T23:54:26.000Z</s:modificationTime> 
   <s:country>US</s:country> 
   <s:language>en</s:language> 
   <s:title>Canon powershot s95 10 mp digital camera with 3.8x wide angle optical image stabilized zoom and 3.0-inch lcd</s:title> 
   <s:description>desc</s:description> 
   <s:link>http://www.amazon.com/Canon-PowerShot-S95-Stabilized-3-0-Inch/dp/B003ZSHNGS</s:link> 
   <s:brand>Canon</s:brand> 
   <s:condition>new</s:condition> 
   <s:gtin>00013803126556</s:gtin> 
   <s:gtins> 
    <s:gtin>00013803126556</s:gtin> 
   </s:gtins> 
   <s:inventories> 
    <s:inventory channel="online" availability="inStock"> 
     <s:price shipping="0.0" currency="USD">340.41</s:price> 
    </s:inventory> 
   </s:inventories> 
   <s:images> 
    <s:image link="http://ecx.images-amazon.com/images/I/519z3AjKzHL._SL500_AA300_.jpg"/> 
   </s:images> 
  </s:product> 
 </entry> 

2 个答案:

答案 0 :(得分:0)

您需要使用获取正确的命名空间。这是未经测试的,但可能会成功:

$url = 'xml-file.xml';
$xml = simplexml_load_file($url);
$namespaces = $xml->entry->getNameSpaces(true);

// Get children of the correct namespace
$s = $xml->entry[0]->children($namespaces['s']);
$title = $s->product->title;

//print
echo '<br/>';
echo $title;

答案 1 :(得分:0)

首先解析名称空间。

$namespaces = $xml->getNameSpaces(true);
$s = $xml->children($namespaces['s']);
echo (string)$s->product->title. "\n";
echo (string)$s->product->images->image->attributes()->link;