I'm looking for a way to get a special type of child out of a xml file with php. the xml:
我正在寻找一种方法,用PHP从xml文件中获取一个特殊类型的孩子。 xml:
<notify type="post" name="Max" />
I want to grab the name out of there. My code: `$sender =
我想把那个名字拿出来。我的代码:`$ sender =
$sender = $node->getChild('notify');
$sender = $sender->getChild('name');
$sender = $sender->getData();
but as i expected it isn't working that way. Thanks in advance for any help
但正如我预期的那样,它并没有那样工作。在此先感谢您的帮助
1 个解决方案
#1
0
You can use an xpath
expression to get the job done. It is like an SQL query for XML.
您可以使用xpath表达式来完成工作。它就像是XML的SQL查询。
$results = $xml->xpath("//notify[@type='post']/@name");
Assuming the XML in $xml
, the expression reads like
假设$ xml中的XML,表达式如下
select all notify nodes,
where their type-attribute is post,
give back the name-attribute.
$results
will be an array, and my code example is made for simplexml
. You can use the same xpath-expression
with DOM
though.
$ results将是一个数组,我的代码示例是针对simplexml。您可以使用与DOM相同的xpath-expression。
Here's the complete code:
这是完整的代码:
$x = <<<XML
<root>
<notify type="post" name="Max" />
<notify type="get" name="Lisa" />
<notify type="post" name="William" />
</root>
XML;
$xml = simplexml_load_string($x);
$results = $xml->xpath("//notify[@type='post']/@name");
foreach ($results as $result) echo $result . "<br />";
Output:
Max
William
see it working: http://codepad.viper-7.com/eO29FK
看它工作:http://codepad.viper-7.com/eO29FK
#1
0
You can use an xpath
expression to get the job done. It is like an SQL query for XML.
您可以使用xpath表达式来完成工作。它就像是XML的SQL查询。
$results = $xml->xpath("//notify[@type='post']/@name");
Assuming the XML in $xml
, the expression reads like
假设$ xml中的XML,表达式如下
select all notify nodes,
where their type-attribute is post,
give back the name-attribute.
$results
will be an array, and my code example is made for simplexml
. You can use the same xpath-expression
with DOM
though.
$ results将是一个数组,我的代码示例是针对simplexml。您可以使用与DOM相同的xpath-expression。
Here's the complete code:
这是完整的代码:
$x = <<<XML
<root>
<notify type="post" name="Max" />
<notify type="get" name="Lisa" />
<notify type="post" name="William" />
</root>
XML;
$xml = simplexml_load_string($x);
$results = $xml->xpath("//notify[@type='post']/@name");
foreach ($results as $result) echo $result . "<br />";
Output:
Max
William
see it working: http://codepad.viper-7.com/eO29FK
看它工作:http://codepad.viper-7.com/eO29FK