Xml PHP获取属性及其子值

Xml PHP获取属性及其子值,php,xml,children,Php,Xml,Children,XML: 这就是我所做的: $type = "Dog"; $category = "Animals"; $name = "dog name"; foreach($xml->name as$name){ $type=$name['type']; $category=$name['category']; echo“Type:$Type Category:$Category”; //为了得到文本,我还没有把它写出来。文本 } 但它不起作用。不要得到任何错误,也不要得到任何输出。有什么想法吗 编辑:

XML:

这就是我所做的:

$type = "Dog";
$category = "Animals";
$name = "dog name";
foreach($xml->name as$name){
$type=$name['type'];
$category=$name['category'];
echo“Type:$Type Category:$Category
”; //为了得到文本,我还没有把它写出来。文本 }
但它不起作用。不要得到任何错误,也不要得到任何输出。有什么想法吗

编辑: 好啊我更改了foreach($xml->name为$name)

到foreach($xml->lesson->name as$name)

所以我得到属性的值。但是现在我不知道如何得到孩子们的价值。 我试过:$xml->lesson->children()

它打印儿童()

已解决:$text=$xml->lesson->children(); echo$文本


问题是:我在其他代码中使用了utf-8,但没有更改它。

编辑::这部分与问题键入有关。如果您直接从编辑xml的地方复制xml,那么部分问题可能是它的格式不正确。您有一个开口
,但您似乎错误地试图用
关闭它


另外,根据根节点设置,
->name
可能是也可能不是$xml对象的子对象。你能发布它的
var\u dump()
并获得一些线索吗?

我认为,你的xml中存在一些问题

->您必须正确关闭课程标签。因为您输入的是
(请参见最后一行),而不是
。如果启动任何标记,则在关闭时应使用相同的标记名

您可以使用此代码从xml中提取值

    foreach($xml->name as $name){
        $type = $name['type'];
        $category = $name['category'];

        echo "Type: $type Category: $category<br>";
        // AND TO get the text, haven't figuered it out yet.. <name ..="" ..="">text</name>
    }
children()作为$key=>$child)
{
$counter++;
$ATTRIBUTE[$counter][“type”]=$child->name->attributes()->type;
$ATTRIBUTE[$counter][“category”]=$child->name->attributes()->category;
$ATTRIBUTE[$counter][“value”]=$child->name;
}
回声“;
打印(属性);
?>

在这里,您将获得阵列中的所有内容。因此,您可以根据您的要求获取。

@MuthuKumaran我认为这是合理暗示的问题之一。简短的代码示例,它没有输出任何内容,有什么问题吗?可能是因为
$xml
指的是
,而不是
?可能是这样,解决方案是?很抱歉,只有我在这里写错了它。@Kilise关于
var_dump()
?:)解决了。它应该是:foreach($xml->lesson->name as$name)
    foreach($xml->name as $name){
        $type = $name['type'];
        $category = $name['category'];

        echo "Type: $type Category: $category<br>";
        // AND TO get the text, haven't figuered it out yet.. <name ..="" ..="">text</name>
    }
<?php

$xmlstring='<lessons>
    <lesson level="1" course="2">
                 <name type="Dog" category="Animals">Dog name</name>
          </lesson>
</lessons>';

$xml = simplexml_load_string($xmlstring);
$ATTRIBUTE=array();
$counter = 0;
foreach($xml->children() as $key=>$child)
  {
    $counter++;
    $ATTRIBUTE[$counter]["type"]=$child->name->attributes()->type;
    $ATTRIBUTE[$counter]["category"]=$child->name->attributes()->category;
    $ATTRIBUTE[$counter]["value"]= $child->name;
  }

echo "<pre>";
print_r($ATTRIBUTE);
?>