使用PHP读取XML样式文件

时间:2012-04-28 08:18:53

标签: php string parsing xml-parsing

我正在尝试从此XML样式文件中检索数据:

<Product_Group>
  <Product_Group_ID>131</Product_Group_ID>
  <Product_Group_Title>Thanks for the Memories</Product_Group_Title>
  <Products>
    <On_Sale_Date>03/01/12 00:00:00.000</On_Sale_Date>
    <ISBN>9780007233694</ISBN>
    <Title>Thanks for the Memories</Title>
    <Format>Paperback</Format>
    <Sub_Format/>
    <CoverImageURL_Small>http://www.harpercollins.com/harperimages/isbn/small/4/9780007233694.jpg</CoverImageURL_Small>
  </Products>
</Product_Group>

我正在使用以下代码,但这似乎没有检索。任何帮助解决这个问题都将受到高度赞赏

$xml = simplexml_load_string($response);
//$xml= $response;
$updates = array();
//loop through all the entry(s) in the feed
for ($i=0; $i<count($xml->Product_Group); $i++)
{
    //get the id from entry
    $ISBN = $xml->entry[$i]->ISBN;

    //get the account link
    $Title = $xml->entry[$i]->Title;

    //get the tweet
    $Product_Group_SEO_Copy = $xml->entry[$i]->Product_Group_SEO_Copy;  
}

1 个答案:

答案 0 :(得分:0)

1)它不是有效的XML。您看到了什么警告?您需要修复它们simplexml_load_string才能正常工作。

例如,</CoverImageURL_Small>应为<CoverImageURL_Small/>

2)假设Product_Group不是您的实际文档根(如果它已经指向$xml并且$xml->Product_Group将不起作用),那么您可以访问每个元素,如< / p>

$xml->Product_Group->Products[$i]->ISBN;

3)处理simplexml时,使用foreach循环通常比for循环更简单

foreach($xml->Product_Group->Products as $p)
{
    $ISBN = $p->ISBN;
    //var_dump($ISBN);
}