douchuanhan8384 2014-12-30 00:30
浏览 45
已采纳

如何使用PHP从XML获取标记的属性?

I have the following XML and code that I try to save it in mySQL. It is working but my problem is that I can not get the product id attribute.

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'product_id' cannot be null

<product id="1111845">
  <name><![CDATA[MadBiker 600]]></name>
  <link>http://demo.com/p.MadBiker-600.1111845.html</link>
  <price_with_vat>107.01</price_with_vat>
...
...
...
</product>

Here is the code

$xml = simplexml_load_file("demo.xml");

   foreach($xml->products->product as $data) {
        $sql = "INSERT INTO products (shop, product_id, name, price, shipping, manufacturer, stock, availability)
            VALUES (:SHOP, :ID, :NAME, :PRICE, :SHIPPING, :MANUFACTURER, :STOCK, :AVAILABILITY)";
        $stmt = $dbh->prepare($sql);

            "ID" => $data->product[id] ,
            "NAME" => $data->name,
            "PRICE" => $data->price_with_vat,

How to do this?

  • 写回答

3条回答 默认 最新

  • douiwn6941 2014-12-30 00:41
    关注

    Your foreach loop iterates over <product> nodes already:

    foreach ($xml->products->product as $data) {
      //...
    }
    

    So in this case, $data already represents <product> and you don't want to use $data->product. Then it is just a matter of referencing the ['id'] attribute by array key on $data itself so:

    "ID" => (string)$data['id']
    

    (Don't forget to cast it to a string - and the other nodes will need the same treatment via (string))

    "NAME" => (string)$data->name,
    "PRICE" => (string)$data->price_with_vat,
    

    The fact that PHP didn't show other warnings suggests you don't have display_errors on. Always when developing code, use

    error_reporting(E_ALL);
    ini_set('display_errors', 1);
    

    Or set them in php.ini.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效