【问题标题】:How to fix XML parsing error with PHP? [duplicate]如何使用 PHP 修复 XML 解析错误? [复制]
【发布时间】:2012-01-28 22:23:32
【问题描述】:

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

我有下面显示的 xml,我想解析出产品标题。当我使用下面的 php 代码时,我得到“Parse error: syntax error, unexpected ':' in /home/content/c/a/s/cashme/html/buylooper/xml.php on line 5”,因为“:”位于标签中。我该如何解决这个问题?

*更新:我已经得到了第一部分的答案,但是在如何解析出 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> 

【问题讨论】:

标签: php xml


【解决方案1】:

首先解析命名空间。

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

【讨论】:

  • 这对除了 s:images 之外的每个人都有效。我认为这是因为“s:images”中没有“s:image”的结束标签。链接是一个属性;如何解析属性?
  • @sharataka s:images 不会显示,因为其中没有文字。通过$s-&gt;product-&gt;images-&gt;image-&gt;attributes()-&gt;link 解析link 属性。查看我的更新。
【解决方案2】:

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

$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;

【讨论】:

  • 这对除了 s:images 之外的每个人都有效。我认为这是因为“s:images”内部没有“s:image”的结束标签。链接是一个属性;如何解析属性?
猜你喜欢
  • 1970-01-01
  • 2018-11-18
  • 2012-12-16
  • 2018-06-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-13
  • 1970-01-01
相关资源
最近更新 更多