PHP 将变量放入 SimpleXML

PHP Put variable in SimpleXML

我对简单XML和变量

有疑问
$num = $categorie['id'];
echo $num; /*return value is 1 or 0*/
$fav = $xml->categorie[$num]->addChild("fav"," ");

我想将 $num 放入类别[$num] 但不起作用。我该怎么做?

我的XML

<?xml version="1.0" encoding="ISO-8859-1"?>
<data>
    <categorie id="0" name="Search">
        <fav>
            <link>Google</link>
            <desc>www.google.fr</desc>
        </fav>
        <fav>
            <link>Orange</link>
            <desc>www.orange.fr</desc>
        </fav>
    </categorie>
    <categorie id="1" name="Social">
        <fav>
            <link>Facebook</link>
            <desc>www.facebook.com</desc>
        </fav>
        <fav>
            <link>Youtube</link>
            <desc>www.youtube.com</desc>
        </fav>
     </categorie>
</data>

我的 php 完整的 php 代码。问题出在 foreach 循环中。我比较类别名称以获取 ID 并将新收藏夹放入正确的类别中。

<?php

$link = $_POST['link'];
$desc= $_POST['desc'];
$cat = $_POST['cat'];

$xml = simplexml_load_file('../data/data.xml');


foreach($xml->categorie as $categorie)
{
    if (strcmp($categorie['name'], $cat) == 0)
    {
        $num = $categorie['id'];
        echo $num;
        $fav = $xml->categorie[$num]->addChild("fav"," ");
        $fav->addChild("link", $link);
        $fav->addChild("desc", $desc);
        $xml->asXML('../data/data.xml');
    }
 }
?>

谢谢

解决方案是使用 intval()

将对象转换为整数
$num = intval($categorie['id']);
$fav = $xml->categorie[$num]->addChild("fav"," ");
$fav->addChild("link", $link);
$fav->addChild("desc", $desc);
$xml->asXML('../data/data.xml');